相关疑难解决方法(0)

C++ STL容器:: clear :: swap

"清除"大型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)

c++ dictionary stl std

2
推荐指数
1
解决办法
2660
查看次数

标签 统计

c++ ×1

dictionary ×1

std ×1

stl ×1