C++ map node handle
阿新 • • 發佈:2018-04-05
erase pan col lap 一個 stream find trac 占用
考慮如下代碼:
#include <iostream> #include <map> #include <string> #include <boost/chrono.hpp> #include <boost/timer/timer.hpp> int main() { std::map<int, std::string> a{ { 1, "one" }, { 2, "two" }, { 3, "buckle my shoe" } }; std::map<int, std::string> b{ { 3, "three" } }; //計算函數調用占用的時間 boost::timer::cpu_timer timer; for (int i=0;i<10000;++i){ { auto ite = a.find(2); auto [k,v] = *ite; b.emplace(std::make_pair(k, v)); a.erase(ite); } { auto ite = b.find(2); auto [k,v]= *ite; a.emplace(std::make_pair(k, v)); b.erase(ite); } } boost::timer::cpu_times time = timer.elapsed(); int wall_time_ = time.wall / 1000000; //納秒轉毫秒 std::cout << "elasped time=" << wall_time_; }
把元素2(key==2)在a,b兩個容器之間移動。涉及到heap的內存分配和釋放。當insert時,發生malloc,當erase時,發生free。
C++17開始,支持無heap動作的元素搬移:
#include <iostream> #include <map> #include <string> #include <boost/chrono.hpp> #include <boost/timer/timer.hpp> int main() { std::map<int, std::string> a{ { 1, "one" }, { 2, "two" }, { 3, "buckle my shoe" } }; std::map<int, std::string> b{ { 3, "three" } }; //計算函數調用占用的時間 boost::timer::cpu_timer timer; for (int i=0;i<10000;++i){ b.insert(a.extract(2)); auto ite = b.find(2); a.insert(b.extract(ite)); } boost::timer::cpu_times time = timer.elapsed(); int wall_time_ = time.wall / 1000000; //納秒轉毫秒 std::cout << "elasped time=" << wall_time_; }
關鍵在於extract函數,它返回一個node handle
C++ map node handle