tags:

views:

324

answers:

3

Hi,

I've a class named Contact and I want to build a data structure of pointers to those objects like a matrix of 127 rows and 20 columns. I've tried to use the std::vector class in this way

std::vector < std::vector<Contact* > > matrix (127, std::vector < Contact* > (20));

then, having declarated the following in the header

std::vector<std::vector<Contact* > > Buckets;

I assign the matrix initialized and declared before to it (this step because basically I don't know how to do it in a more clear and short way):

Buckets = matrix;

but using the push_back function like

Buckets[pot].push_back(cont_temp);

after a while produces an error ("terminate called after throwing an instance of 'std::bad_alloc'") and I don't know how to fix it.

Is there any other better way to instantiate and initialize the matrix? Would you suggest other solutions instead of using a vector of vectors (a boost::multiarray..?) ?

thanks (sorry for the stupid question, I'm a poor student:)

Edit: I've found the error (just an assignment out of bounds). If you have general suggestions for this kind of data structure I'm still here...

A: 

Are the Contacts in the matrix dynamically allocated? If so, when you say:

Buckets = matrix;

you end up with two pointers pointing to the same dynamically allocated object, which can only lead to trouble down the line. You should use vectors of smart pointers, such as Boost's shared pointers, instead.

anon
Be careful not to use the std::auto_ptr though since its not save to use in standard containers due to it's ownership transfer semantics
Foo42
+2  A: 

When you say "after a while", what does that mean? std::bad_alloc means you ran out of memory. Do you have a loop that gobbles up memory?

Dave R
A: 

If you only mean to use a 2d matrix of known sizes, you may use a simple array :

(Contact*) matrix[127][20];

Of course, this approach does not work if sizes can be determined or change after compilation. In this case, i suggest you turn to boost libraries, multi_array in particular.

See here for a short example or there for the complete documentation.

typedef boost::multi_array<Contact*, 2> ContactContainer;
ContactContainer matrix(boost::extents[127][20]);
Benoît