0

So I have a class Board header as followed:

class Board
    {
        std::vector<std::vector<char>> _board;
        uint _rows;
        uint _cols;

    public:
        Board();
}

And I have this default constructor:

    Board::Board()
    {
        _rows = 0;
        _cols = 0;
        _board.push_back(vector<char>(1, '_'));
    }

And I just don't understand the syntax of this line of code:

 _board.push_back(vector<char>(1, '_'));

I mean, it does it's job: it adds a '_' at the end of the first row as it should. But from what I've read about the method push_back() I don't understand why it's not just

_board.push_back('_');

PS: push_back() signature is:

void push_back (const value_type& val);

EDIT: The message error I get when using board.push_back(''); is:

error: no matching member function for call to 'push_back'

Jewgah
  • 51
  • 8
  • 4
    `_board` is a vector of vectors, so the things you push to it have to be vectors. `'_'` is a char, not a vector. – Nate Eldredge Mar 21 '21 at 22:20
  • So the vector inside is a casting ? And why is this "1" important ? when I use _board.push_back(vector('_') it's not the same, why ? – Jewgah Mar 21 '21 at 22:23
  • 1
    It's not a cast, it's a constructor. `vector(1, '_')` constructs a `vector` of size 1 whose single element is initialized to `'_'`. If you replace 1 by 7 you will get a vector of size 7 instead, all of whose elements are initialized to `'_'`. But `std::vector` doesn't have a constructor that just takes one value and assumes the size to be 1; the designers apparently didn't think that would be useful. – Nate Eldredge Mar 21 '21 at 22:27
  • Ok it's a constructor then ! So my misunderstanding was about vector and not about push_back(). Thanks ! – Jewgah Mar 21 '21 at 22:29
  • 2
    You can also use curly braces, ***i.e.*** direct-brace-initialization, to construct the inner vector `_board.push_back({'_'});` – anastaciu Mar 21 '21 at 22:31
  • Good to know, Thanks! – Jewgah Mar 21 '21 at 22:33

1 Answers1

0

The value type of _board is std::vector<char>, not char.

The value type of _board.front() is char.

    _rows = 0;
    _cols = 0;
    _board.push_back(vector<char>(1, '_'));

that doesn't make much sense. A 0x0 board doesn't have a _ in it.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524