C++ STL 容器 ::清除 ::交换
C++ STL container ::clear ::swap
"清除"大型 STL 容器的最快方法是什么?在我的应用程序中,我需要处理大尺寸std::map
,例如,10000个元素。
我已经测试了以下 3 种清除std::map
的方法。
- 每次需要时创建一个新容器。
- 调用
map::clear()
方法。 - 调用
map::swap()
方法。
似乎::swap()
给出了最好的结果。谁能解释一下为什么会这样?是否可以肯定地说,使用map::swap()
方法是"清除"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
您没有正确测试swap
情况。您需要销毁交换到映射才能说明所有时间。尝试以下方法之一:
{ 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);
您是否因为遇到
性能问题而问这个问题,并且您已经确定您的程序花费了太多时间清除地图?如果你还没有这样做,那么只需使用 map::clear() 或每次创建新的局部变量,以对你的程序最自然和最直接的方式。交换技巧是一种优化,除非您根据经验确定需要优化,否则浪费时间进行优化几乎没有意义。
如果您已经确定了性能问题,那么您已经有了确定哪种方法最能解决该问题的工具。
相关文章:
- C++嵌套if语句,基本货币交换
- shell排序中的交换和比较
- 清除前检查矢量
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 通过交换元素使数组相同
- 如何使 std::sort 在 std::swap 和我的命名空间的模板化交换之间没有名称冲突?
- ifstream文件在从行中读取时被清除
- 交换运算符 + 重载会导致无限递归
- 为什么 std::reduce 需要交换性?
- WINAPI 注册应用程序重新启动时不清除打开的套接字
- 复制和交换习惯用法与移动操作之间的交互
- C++ - 没有自定义交换功能的移动分配运算符?
- 如何在数组中交换最小和最大的位置?
- 如何清除/清空已打开的文件C++
- 尽管一切看起来都很好,但值不会交换
- C++交换来自同一类成员的参数值,处理多个类
- 插入排序的最小交换
- 我应该清除作为参数传入的()容器,还是交换一个新对象
- C++ STL 容器 ::清除 ::交换
- 交换可以用来清除std::set作为向量吗