zoukankan      html  css  js  c++  java
  • vector优化

    C++的stdvector使用优化

    #include<iostream>
    #include<vector>
    using namespace std;
    
    class Vectex
    {
    private:
    	int x, y, z;
    public:
    	Vectex(int x,int y,int z)
    		: x(x),y(y),z(z)
    	{
    	}
    	Vectex(const Vectex& vectex)
    	{
    		cout << "拷贝" << endl;
    	}
    };
    int main()
    {
    	vector<Vectex>v;
    	v.push_back({ 1,2,3 });
    	v.push_back({ 4,5,6 });
    	v.push_back({ 7,8,9 });
    }
    
    • 执行6次拷贝

    提前告诉它有多少数据

    #include<iostream>
    #include<vector>
    using namespace std
    
    class Vectex
    {
    private:
    	int x, y, z;
    public:
    	Vectex(int x,int y,int z)
    		: x(x),y(y),z(z)
    	{
    	}
    	Vectex(const Vectex& vectex)
    	{
    		cout << "拷贝" << endl;
    	}
    };
    int main()
    {
    	vector<Vectex>v;
    	v.reserve(3);//分配三个内存空间
    	v.push_back({ 1,2,3 });
    	v.push_back({ 4,5,6 });
    	v.push_back({ 7,8,9 });
    }
    
    • 执行3次拷贝

    只传递构造函数参数列表

    #include<iostream>
    #include<vector>
    using namespace std
    
    class Vectex
    {
    private:
    	int x, y, z;
    public:
    	Vectex(int x,int y,int z)
    		: x(x),y(y),z(z)
    	{
    	}
    	Vectex(const Vectex& vectex)
    	{
    		cout << "拷贝" << endl;
    	}
    };
    int main()
    {
    	vector<Vectex>v;
    	v.reserve(3);
    	v.emplace_back( 1,2,3 );
    	v.emplace_back( 4,5,6 );
    	v.emplace_back( 7,8,9 );
    }
    
    • 执行了0次拷贝
  • 相关阅读:
    Mysql主从同步延迟问题及解决方案
    elasticsearch 查询过程
    RPC(Remote Procedure Call):远程过程调用
    windows
    设计模式
    Linux Safe
    AS
    开机启动
    springboot打包部署
    【Linux】Linux 常用命令汇总
  • 原文地址:https://www.cnblogs.com/chengmf/p/14890419.html
Copyright © 2011-2022 走看看