user3102241
user3102241

Reputation: 497

vector inside a map is clear safe?

Just a quick question, if you have say:

using namespace std;

map< int, vector< string > > map1;

or maybe even:

map< int, map< int, vector< string > > > map2;

and just so you get the right idea:

map< int, map< int, map< int, vector< string > > > > map3;

if I do just:

map1.clear();
map2.clear();
map3.clear();

Is it safe in that it will empty everything in the map and its nested maps, vectors, lists, etc.?

Note: I know if you use pointers you need to manually go through and delete or if the map goes out of scope it should be fine too I'm only particularly interested in this case when in scope and on the stack.

Upvotes: 5

Views: 4025

Answers (2)

Yes, a map will destruct all components.

If its components are STL containers, their destructors will clear the containers.

Read more about STL containers notably about destructor of std::map

Upvotes: 5

Danvil
Danvil

Reputation: 23031

Yes this is perfectly safe. STL containers take care of memory management.

However, if you store pointers to objects which you allocated youself, you also have to delete them yourself:

std::vector<MyClass*> vec;
vec.push_back(new MyClass());
vec.clear(); // you get a memory leak here because you did not delete the object you allocated.

Upvotes: 2

Related Questions