tags:

views:

164

answers:

3

I'm trying to do something like:

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

class Clickomania
{
    public:
        Clickomania();
        std::vector<std::vector<int> > board;
        bool move(int, int);
        bool isSolved();
        void print();
        void pushDown();
};

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?

+2  A: 

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;
}
Eddy Pronk
Why the downvote to this one?
the_drow
Maybe because it had nothing to do with getting vector to work in the above code like the question asked. I don't know. I think that downvoting it is a bit harsh - this answer *is* potentially helpful after all - but it doesn't technically answer the question.
Jonathan M Davis
+1, I don't find there is any need to down vote a helpful answer even if it is not exactly answering the OP's question.
Anders K.
A: 

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.

sanimalp
That is exactly what the OP does.
James McNellis
yeah just noticed that.. don't know how i missed it.
sanimalp
+1  A: 

Compiling your code with g++, the error I get is that neither srand() nor rand() were declared. I had to add #include <cstdlib> for the code to compile. But once I did that, it worked just fine. So, I'd say that other than adding that include statement, your code is fine. You're initializing the vector correctly.

Perhaps the code you have doesn't quite match what you posted? I would assume that if your actual code didn't include cstdlib, that you would have quickly understood that that was the problem rather than something with vector. So, if your code doesn't quite match what you posted, maybe that's the problem. If not, what compiler are you using?

Jonathan M Davis