views:

94

answers:

3

Take a variable length struct (if this were a real program, an int array would be better):

#include <vector>
struct list_of_numbers(){
  int length;
  int *numbers; //length elements.
};
typedef std::vector<list_of_numbers> list_nums; //just a writing shortcut

(...)

And build a vector out of it:

list_nums lst(10); //make 10 lists.
lst[0].length = 7; //make the first one 7 long.
lst[0].X = new int[7]; //allocate it with new[]

(...)

The above works for g++ in ubuntu. The new() calls are needed to avoid segfaults. Can the lst vector be deleted all at once when it is no longer needed, or will the new calls cause a memory leak? It would be tedious to manually delete() all of the parts called with new().

A: 

In general, you would want to put cleanup code in the destructor of the object (~list_of_numbers()) and memory creating code in the constructor (list_of_numbers()). That way these things are handled for you when the destructor is called (or when the object is created).

ezpz
You would also have to implement the copy constructor and copy assignment operator.
James McNellis
If the class is copyable.
DeadMG
@DeadMG: If it's not copyable, you aren't going to be putting instances of it in a vector :-).
James McNellis
I like this answer. It actually gets to the point. And you read what I said:"(if this were a real program, an int array would be better)". This was actually the expected answer.
Kevin Kostlan
@James McNellis: Depends on if you're using C++0x.
DeadMG
@DeadMG: Ok, so if you have a move-aware containers library implementation, you need either to implement the copy constructor and copy assignment operator OR the move constructor and the move assignment operator. You still have to do _something_ because the implicitly declared special member functions aren't going to do what we need them to do.
James McNellis
+4  A: 

The typical ways to do this in C++ would be to define constructors and destructors and assignment operators for the list_of_numbers struct that take care of the memory management, or (much better) use a std::vector<int> for the numbers field and get rid of the length field.

But if you do that, you may as well get rid of the struct entirely, and just do this:

#include <vector>
typedef std::vector<int> list_ints;
typedef std::vector<int_ints> list_lists;

(...)

list_lists lst(10); // make 10 lists.
lst[0].resize(7);   // set length of the zeroth list to 7
Kristopher Johnson
small code typo typedef std::vector<int_ints> list_lists; -> typedef std::vector<list_ints> list_lists;
David
+1  A: 

Why not just use a vector of vector of int? That's it's job. You should not be calling new outside of a dedicated class.

DeadMG