I have a main vector container which will be passed vectors of different lengths
I would need to sum up all the first elements of the different vectors and delete the first element.
I am having difficulty removing the empty vector from my main container.
could you please show me how to do it thanks.
How do to remove the empty vector from my main container and free the memory.
int main()
{
vector< vector<int> > container;
vector<int> v1(2,1);
vector<int> v2(4,2);
vector<int> v3(6,3);
container.push_back(v1);
container.push_back(v2);
container.push_back(v3);
// just checking sizes of each container
for (int i=0; i < container.size(); i++)
{
cout << container[i].size() << endl;
}
int x = 2;
int temp = 0;
int contain = container.size();
while(x > 1)
{
for (int i=0; i < contain; i++)
{
//need to add all first elements of the vector
temp += container[i][0];
//delete first element after reading
if(container[i].size() > 1)
{
container[i].erase(container[i].begin());
}
// delete empty vector inside container.
// new vectors can come in here
container.push_back(v1);
contain = container.size();
cout << temp << endl;
temp = 0;
// if no more vectors are inserted stop program
if(container.size() == 0)
{
x = 0;
break;
}
cin >> x;
return 0;
}
It looks like your algorithm for removing elements from the vectors contained in the "container" vector is wrong. you have
1 2 3 4 5 6
//delete first element after reading
if(container[i].size() > 1)
{
container[i].erase(container[i].begin());
}
your statement only deletes the first element from vectors with size greater than one, if your vector only has one element in it then it will never be deleted. So your algorithm will never have empty vectors that need to be erased.
try
if(container[i].size() > 0)
after you correct that, you can delete an empty vector by searching for empty vectors in "container" and using the erase command to take them out.
(i thinK)