Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Dynamic allocation of vectors in vector?

Tags:

c++

stl

I'm working with vector now and I have an interesting situation which I need to help with.

I have a vector of vectors, defined as following:

vector< vector<int> > list;

I am loading numbers from standard input using cin >> helpVar; and everytime when I get 0 (zero) I want to create new vector of ints, which will be put into this "main container" list.

Of course I don't know, how many times the zero number will appear - it's user-dependend. So I also don't know, how much vectors the program will add.

But I don't know, how exactly to do it. If I used C# or other garbage collection-like language, I would probably just write:

if(helpVar == 0)
{
   list.push_back(new vector<int>);
}

But this construction doesn't work in C++.

So my question is, how should I deal with this situation to make it working? Or am I just thinking about it wrong and it should be done in another way?

Thanks for the answers.

like image 267
Miroslav Mares Avatar asked Dec 28 '25 15:12

Miroslav Mares


2 Answers

list.push_back(vector<int>());

vector<int>() creates a temporary vector<int> object and initializes it (i.e., it calls the default constructor for that object). push_back then copies that temporary object into the list.

In C# (and "other garbage collected languages"), new is used to create new objects, whose lifetimes are controlled by the garbage collector.

In C++, new is only used to dynamically allocate an object (and you are responsible for managing its lifetime, by using a smart pointer). The syntax T() (where T is the name of a type) is used to create a temporary object.

like image 102
James McNellis Avatar answered Dec 31 '25 07:12

James McNellis


In C++11:

list.emplace_back();

In C++03:

list.push_back(std::vector<int>());

new dynamically allocates an object and gives you a pointer to it; vector::push_back() takes a reference to an object, which it will copy. Only use new when you want to dynamically allocate the object yourself - that's not necessary if you're using containers to do that for you. When you do use new, make sure you use a smart pointer (or very carefully written code) to delete it when you've finished with it.

like image 28
Mike Seymour Avatar answered Dec 31 '25 07:12

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!