C++ STL 容器 ::清除 ::交换

C++ STL container ::clear ::swap

本文关键字:清除 交换 容器 STL C++      更新时间:2023-10-16

"清除"大型 STL 容器的最快方法是什么?在我的应用程序中,我需要处理大尺寸std::map,例如,10000个元素。

我已经测试了以下 3 种清除std::map的方法。

  • 每次需要时创建一个新容器。
  • 调用map::clear()方法。
  • 调用map::swap()方法。

似乎::swap()给出了最好的结果。谁能解释一下为什么会这样?是否可以肯定地说,使用map::swap()方法是"清除"std::map的正确方法?其他STL容器是否相同,例如setvectorlist等?

    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() 或每次创建新的局部变量,以对你的程序最自然和最直接的方式。交换技巧是一种优化,除非您根据经验确定需要优化,否则浪费时间进行优化几乎没有意义。

如果您已经确定了性能问题,那么您已经有了确定哪种方法最能解决该问题的工具。