C ++ STL container :: clear :: swap [英] C++ STL container ::clear ::swap
问题描述
什么是清除大型STL容器的最快方法?在我的应用程序中,我需要处理大尺寸的 std :: map
,例如10000元素。
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已经测试了以下3种方法来清除 std :: map
。
I have tested the following 3 methods to clear a std::map
.
- 创建一个新的容器,每次我需要它。
- 调用
map :: clear()
方法 - 调用
map :: swap()
方法。
- Create a new container every time I need it.
- Calling
map::clear()
method. - Calling
map::swap()
method.
:: swap()
给出最好的结果。有人可以解释为什么会这样吗?说,使用 map :: swap()
方法是清除std :: map的正确方法是否安全?其他STL容器是一样的,例如 set
, vector
, list
等。
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
推荐答案
您没有正确测试 swap
case。您需要交换映射被销毁以便占用所有的时间。请尝试以下方法之一:
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.
或
// temporary gets destroyed at the semi-colon
std::map<int, int>().swap(test_map);
这篇关于C ++ STL container :: clear :: swap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!