C++ STL container ::clear ::swap
c++, dictionary, std, stl
Solution
You aren't properly testing the `swap` case. You need for the swap-to map to be destroyed in order to account for all of the time. Try one of these:
{ std::map<something, something_else> test_map2;
test_map.swap(test_map2);
} // test_map2 gets destroyed at the closing brace.
or
// temporary gets destroyed at the semi-colon
std::map<int, int>().swap(test_map);
Problem
What's the fastest way to "clear" a large STL container? In my application, I need to deal with large size `std::map`, e.g., 10000 elements. I have tested the following 3 methods to clear a `std::map`. - Create a new container every time I need it. - Calling `map::clear()` method. - Calling `map::swap()` method. It seems that `::swap()` gives the best result. Can anyone explain why this is the case, please? Is it safe to say that using `map::swap()` method is the proper way to "clear" a std::map? Is it the same for other STL containers, e.g., `set`, `vector`, `list`, etc. ``` m_timer_start = boost::posix_time::microsec_clock::local_time(); // test_map.clear(); test_map.swap(test_map2); for (int i = 0; i< 30000; i++){ test_map.insert(std::pair<int, int>(i, i)); } // std::map<int, int> test_map_new; // for (int i = 0; i< 30000; i++){ // test_map_new.insert(std::pair<int, int>(i, i)); // } m_timer_end = boost::posix_time::microsec_clock::local_time(); std::cout << timer_diff(m_timer_start, m_timer_end).fractional_seconds() << std::endl; // microsecond ```