• 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;
    	}
    
    }
    

      

     

  • 相关阅读:
    flask 指定前端文件路径以及静态文件路径
    pycharm git修改密码
    Web应用搭建
    python学习
    python解析jSON文件
    通过DLNA将电脑视频投射到电视屏幕
    U盘自动复制文件
    kali PIN码破解
    mdk3洪水攻击教程
    sqlmap(网站数据库注入)
  • 原文地址:https://www.cnblogs.com/alexYuin/p/12031975.html
Copyright © 2020-2023  润新知