views:

437

answers:

2

Hello, I am trying to create a vector that contains pointers, each pointer points to another vector of a type Cell which I have made using a struct. The for loop below allows me to let the user define how many elements there are in the vector of pointers. Here's my code:

vector< vector<Cell>* >  vEstore(selection);
for (int t=0; t<selection; t++)
{
 vEstore[t] = new vector<Cell>; 
 vEstore[t]->reserve(1000);
}

This, I think, gives me a vector of pointers to destination vectors of the type Cell. This compiles but I'm now trying to push_back onto the destination vectors and can't see how to do it.

Since the destination vector is of the type Cell which is made from a type as follows:

struct Cell
{
    unsigned long long lr1;
    unsigned int cw2;
};

I can't work out how to push_back onto this destination vector with 2 values?

I was thinking ...

binpocket[1]->lr1.push_back(10);
binpocket[1]->cw2.push_back(12);

As I thought this would dereference the pointer at binpocket[1] revealing the destination array values, then address each element in turn. But it doesn't compile.

can anyone help ...but this only has one value and doesn't compile anyway.

+6  A: 
Cell cell = { 10, 12 };
binpocket[1]->push_back(cell);

Alternatively, you can give your struct a constructor.

struct Cell
{
    Cell() {}
    Cell(unsigned long long lr1, unsigned int cw2)
        : lr1(lr1), cw2(cw2)
    {
    }

    unsigned long long lr1;
    unsigned int cw2;
};

Then you could do

binpocket[1]->push_back(Cell(10, 12));

Note that long long is non-standard (yet), but is a generally accepted extension.

avakar
Thanks very much both
Columbo
This is probably a really stupid question but why do you have the constructor twice, once empty?
Columbo
If you provide no constructors, the compiler will create an empty default (i.e. parameter-less) constructor for you. That means you can do `Cell cell;`. By providing a custom constructor, the compiler won't create the default constructor for you. That's why I provided it. You don't have to do that, if you don't want to do `Cell cell;`.
avakar
I see, thanks avakar.
Columbo
+2  A: 

Give your cell a constructor:

struct Cell
{
    unsigned long long lr1;
    unsigned int cw2;

    Cell( long long lv, int iv ) : lr1(lv), cw2(iv ) {}
};

You can now say things like:

binpocket[1]->push_back( Cell( 10, 12 ) );

BTW, note that long long is not standard C++.

anon