123
123

Reputation: 8951

How to initialize 2d vector

I'm building a tictactoe game, but I can't seem to figure out how to initialize a 2d vector. I know how to do this for a 1d vector, and I assumed a 2d vector would operate on the same principles, but this code doesn't work:

vector<vector<int>> PossibleWins[8][3] = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};

I've tried a few variations of this, but I'm not having any luck. The compiler says no viable conversion from int to vector<vector<int>>

Upvotes: 0

Views: 1030

Answers (3)

구경호
구경호

Reputation: 1

how about doing like this

vector< vector<char> > board = { {'U','R','L','P','M'},{'X','P','R','E','T'},{'G','I','A','E','T'},{ 'X','T','N','Z','Y' },{ 'X','O','Q','R','S' } };

Upvotes: 0

Paraboloid87
Paraboloid87

Reputation: 428

You should do it like this:

std::vector<std::vector<int>> PossibleWins {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};

Upvotes: 1

R Sahu
R Sahu

Reputation: 206567

When you use

vector<vector<int>> PossibleWins[8][3] = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};

The compiler thinks everyone of those numbers represents a std::vector<std::vector<int>>. It complains since the numbers cannot be used to initialize std::vector<std::vector<int>>.

Compare that with how you would initialize a 2D array.

int PossibleWins[8][3] = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};

That works since each of the numbers is an int.

To initialize a vector of vectors to represent a 2D array, you need to use

vector<vector<int>> PossibleWins{{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};

Upvotes: 1

Related Questions