近日在youtube视频上看到关于vector中emplace_back与push_back区别的介绍,深感自己在现代c++中还是有不少遗漏的知识点,遂写了段代码,尝试比较两者的差别。
#include <iostream> #include <vector> #include <functional> #include <chrono> class item { public: item(std::string name, bool display = true):name(name), display(display) { if (display) std::cout << "constructor: " << name << std::endl; } item(const item& item):name(item.name), display(item.display) { if (item.display) std::cout << "copy consturctor: " << item.name << std::endl; } private: std::string name; bool display; }; void calculate(std::vector<item>& v, int count, std::function<void()> const& f) { clock_t begin_time = clock(); for (auto i = 0; i < count; i++) { f(); } std::cout << float(clock() - begin_time) / clocks_per_sec << std::endl; } int main() { std::vector<item> v; v.reserve(2); v.push_back(item("push_back")); v.emplace_back("emplace_back", true); v.clear(); int count = 100000; v.reserve(count); calculate(v, count, [&]() { v.push_back(item("push_back", false)); }); v.clear(); calculate(v, count, [&]() { v.emplace_back("emplace_back", false); }); }
constructor: push_back copy consturctor: push_back constructor: emplace_back 0.431 0.28
如对本文有疑问, 点击进行留言回复!!
Visual Studio运行C++代码遇到:“error LNK2019: 无法解析的外部符号 _WinMain@16,该符号在函数 ___tmainCR...“问题,该怎么办?
斯坦福CS106B——StanfordCPPLib在Qt Creator上的配置
2020 7.12 -- 7.13 两场牛客多校 + 两场 unrated的cf的补题
网友评论