“清理”大型 STL 容器的最快方法是什么?在我的应用程序中,我需要处理大尺寸std::map
,例如 10000 个元素。
我测试了以下3种方法来清除std::map
.
- 每次需要时创建一个新容器。
- Calling
map::clear()
method.
- Calling
map::swap()
method.
看起来::swap()
给出最好的结果。谁能解释一下为什么会出现这种情况吗?可以肯定地说使用map::swap()
方法是“清除” std::map 的正确方法吗?其他 STL 容器是否相同,例如,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
案件。您需要销毁交换地图才能计算所有时间。尝试以下其中一项:
{ 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)