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.
vector<int>()creates a temporaryvector<int>object and initializes it (i.e., it calls the default constructor for that object).push_backthen copies that temporary object into thelist.In C# (and “other garbage collected languages”),
newis used to create new objects, whose lifetimes are controlled by the garbage collector.In C++,
newis only used to dynamically allocate an object (and you are responsible for managing its lifetime, by using a smart pointer). The syntaxT()(whereTis the name of a type) is used to create a temporary object.