260*_*607 2 c++ dictionary stl std
"清除"大型STL容器的最快方法是什么?在我的应用程序中,我需要处理大尺寸std::map,例如10000个元素.
我已经测试了以下3种方法来清除a std::map.
map::clear()方式.map::swap()方式.它似乎::swap()给出了最好的结果.有谁可以解释为什么会这样,拜托?可以说使用map::swap()method是"清除"std :: map的正确方法吗?它是同其他STL容器,例如set,vector,list等.
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
Run Code Online (Sandbox Code Playgroud)
您没有正确测试swap案例.您需要销毁swap-to地图才能占用所有时间.尝试以下方法之一:
{ std::map<something, something_else> test_map2;
test_map.swap(test_map2);
} // test_map2 gets destroyed at the closing brace.
Run Code Online (Sandbox Code Playgroud)
要么
// temporary gets destroyed at the semi-colon
std::map<int, int>().swap(test_map);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2660 次 |
| 最近记录: |