C++ clearing a std::map with internal lists

286 views Asked by At

If I have a std::map like this std::map<int, std::list<int> > myMap;

After the map has been populated with lists and I wish to clear all elements later, is it simply enough to do myMap.clear(); , or should I first go through each element in the map and clear each list first?

1

There are 1 answers

1
lubgr On

No, you can just use myMap.clear(). It takes care of all necessary cleanup.

More precisely, it deletes each node in the tree, and as every node is a std::pair<int, std::list<int>>, the deletion causes the destructor std::list::~list to be invoked - and this destructor takes care of the cleanup of the data it owns.