C++ STL container ::clear ::swap

妖精的绣舞 提交于 2019-12-06 07:10:15

You aren't properly testing the swap case. You need for the swap-to map to be destroyed in order to account for all of the time. Try one of these:

{ 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);

Are you asking this because you're having a performance problem and you have identified that your program is spending too much time clearing your maps? If you haven't done this then just use map::clear() or create new local variables each time, whichever is most natural and direct for your program. The swap trick is an optimization and there's little point in wasting time optimizing unless you're certain you need to, based on experience.

If you have identified a performance issue then you've already got the tool to determine which of your methods best addresses it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!