Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare and initialize a 2d int vector in C++?

Tags:

c++

I'm trying to do something like:

#include <iostream>
#include <vector>
#include <ctime>

class Clickomania
{
    public:
        Clickomania();
        std::vector<std::vector<int> > board;
};

Clickomania::Clickomania()
    : board(12, std::vector<int>(8,0))             <<<<<<<
{

    srand((unsigned)time(0));

    for(int i = 0; i < 12; i++)
    {
        for(int j = 0; j < 8; j++)
        {
            int color = (rand() % 6) + 1;
            board[i][j] = color;
        }
    }
}

However, apparently I can't initialize the "board" vector of vectors this way.

How can I create a public member of a 2d vector type and initialize it properly?

like image 861
FrankTheTank Avatar asked Apr 28 '10 23:04

FrankTheTank


2 Answers

you should use the constructor that allows you to specify size and initial value for both vectors which may make it a bit easier altogether.

something like:

vector<vector<int>> v2DVector(3, vector<int>(2,0));

should work.

like image 73
sanimalp Avatar answered Sep 21 '22 20:09

sanimalp


Use a matrix instead:

(Basic example from boost documentation)

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>

int main () {
    using namespace boost::numeric::ublas;
    matrix<double> m (3, 3);
    for (unsigned i = 0; i < m.size1 (); ++ i)
        for (unsigned j = 0; j < m.size2 (); ++ j)
            m (i, j) = 3 * i + j;
    std::cout << m << std::endl;
}
like image 36
Eddy Pronk Avatar answered Sep 25 '22 20:09

Eddy Pronk