Connecting Tech Pros Worldwide Forums | Help | Site Map

Clearing multidimensional STL vector

Sascha T.
Guest
 
Posts: n/a
#1: Jul 23 '05

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[i].resize(3);
}

vI.clear();
}

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

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

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

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

Thanks in advance

Yours

ST

Ioannis Vranos
Guest
 
Posts: n/a
#2: Jul 23 '05

re: Clearing multidimensional STL vector


Sascha T. wrote:
[color=blue]
> 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;[/color]


That is a "2-dimensional" vector.

[color=blue]
> vI.resize(10);[/color]


This makes the "rows" 10.


[color=blue]
> for(int i(0); i<10; i++)
> {
> vI[i].resize(3);
> }[/color]


This makes the "columns" 3.


[color=blue]
>
> vI.clear();
> }
>
> ---------------------
>
> Will vI.clear() really free *all* vI[i], too?[/color]



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




[color=blue]
>
> Or will I need another loop just before calling vI.clear() to sequentially
> delete all vI[i]: such as:
>
> --------------
> for(int i(0); i<10; i++)
> {
> vI[i].clear();
> }[/color]


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();
}




--
Ioannis Vranos

http://www23.brinkster.com/noicys
Rolf Magnus
Guest
 
Posts: n/a
#3: Jul 23 '05

re: Clearing multidimensional STL vector


Sascha T. wrote:
[color=blue]
>
> 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[i].resize(3);
> }
>
> vI.clear();
> }
>
> ---------------------
>
> Will vI.clear() really free *all* vI[i], too?[/color]

It will destroy all vI[i], part of which is destroying all the elements in
each of them, so the answer is yes.
[color=blue]
> Or will I need another loop just before calling vI.clear() to sequentially
> delete all vI[i]: such as:
>
> --------------
> for(int i(0); i<10; i++)
> {
> vI[i].clear();
> }
> --------------[/color]

No need for that.

Sascha T.
Guest
 
Posts: n/a
#4: Jul 23 '05

re: Clearing multidimensional STL vector



Got it, and thank you for that:
[color=blue]
> vector<vector<int> > vI(10, vector<int>(3));[/color]


Cheers

ST
Closed Thread