zoukankan      html  css  js  c++  java
  • C++ std::vector emplace_back 优于 push_back 的理由

    #include <iostream>
    #include <vector>
    #include <chrono>
    #include <windows.h>
    
    using namespace std;
    using namespace std::chrono;
    
    // 要考虑 copy ctor 和 copy opt=
    
    class Item
    {
    public:
    	Item() = delete;
    
    	Item(const Item & ths);
    
    	Item(std::string str);
    
    	Item & operator = (const Item & ths);
    
    	~Item();
    
    private:
    
    };
    
    Item::Item(const Item & ths)
    {
    	//cout << "copy ctor" << endl;
    	Sleep(2);
    }
    
    Item::Item(std::string str)
    {
    	//cout << str.c_str() << endl;
    	Sleep(2);
    }
    
    Item & Item::operator=(const Item & ths)
    {
    	//cout << "copy opt=" << endl;
    	Sleep(2);
    }
    
    Item::~Item()
    {
    }
    
    int main() 
    { 
    	{
    		auto tbegin = steady_clock::now();
    		std::vector<Item> vec8;
    		for (size_t i = 0; i < 2000; ++i)
    			vec8.push_back(Item("111"));
    
    
    		auto used = duration_cast<milliseconds>(steady_clock::now() - tbegin);
    		std::cout << used.count() << "ms" << std::endl;
    	}
    
    	{
    		auto tbegin = steady_clock::now();
    		std::vector<Item> vec8;
    		for (size_t i = 0; i < 2000; ++i)
    			vec8.emplace_back("222"); // 少一次 copy ctor 的调用
    
    		auto used = duration_cast<milliseconds>(steady_clock::now() - tbegin);
    		std::cout << used.count() << "ms" << std::endl;
    	}
    
    }
    

      

     

  • 相关阅读:
    常见动态规划题目详解
    回溯法常见题目总结
    AWK语法入门
    JavaScript深拷贝—我遇到的应用场景
    git代码版本回退
    Rem实现移动端适配
    Weex了解
    Vue.js入门学习
    今日小结—304状态码,数组去重
    js今日小结—Ajax、前端安全、GET&POST、闭包、HTTPS
  • 原文地址:https://www.cnblogs.com/alexYuin/p/12031975.html
Copyright © 2011-2022 走看看