Clearing multidimensional STL vector

S

Sascha T.

Hi!

I didn't get the idea of exactly *how* such an array of vectors work.

Consider this minimal code:
--------------------

#include <vector>
using namespace std;

int main ()
{
vector< vector<int> > vI;
vI.resize(10);
for(int i(0); i<10; i++)
{
vI.resize(3);
}

vI.clear();
}

---------------------

Will vI.clear() really free *all* vI, too?

Or will I need another loop just before calling vI.clear() to sequentially
delete all vI: such as:

--------------
for(int i(0); i<10; i++)
{
vI.clear();
}
--------------

Thanks in advance

Yours

ST
 
I

Ioannis Vranos

Sascha said:
Hi!

I didn't get the idea of exactly *how* such an array of vectors work.

Consider this minimal code:
--------------------

#include <vector>
using namespace std;

int main ()
{
vector< vector<int> > vI;


That is a "2-dimensional" vector.

vI.resize(10);


This makes the "rows" 10.


for(int i(0); i<10; i++)
{
vI.resize(3);
}



This makes the "columns" 3.


vI.clear();
}



It destroys all vector<int> objects contained in the vector.




Or will I need another loop just before calling vI.clear() to sequentially
delete all vI: such as:

--------------
for(int i(0); i<10; i++)
{
vI.clear();
}



No, this is not needed.


Your code in better shape:


#include <vector>

int main ()
{
using namespace std;

vector<vector<int> > vI(10, vector<int>(3));


// Not needed here
// vI.clear();
}
 
R

Rolf Magnus

Sascha said:
Hi!

I didn't get the idea of exactly *how* such an array of vectors work.

Consider this minimal code:
--------------------

#include <vector>
using namespace std;

int main ()
{
vector< vector<int> > vI;
vI.resize(10);
for(int i(0); i<10; i++)
{
vI.resize(3);
}

vI.clear();
}


It will destroy all vI, part of which is destroying all the elements in
each of them, so the answer is yes.
Or will I need another loop just before calling vI.clear() to sequentially
delete all vI: such as:

--------------
for(int i(0); i<10; i++)
{
vI.clear();
}
--------------


No need for that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top