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次拷贝
  • 相关阅读:
    Java守护线程Daemon
    在for循环中创建双向链表
    Java泛型-官方教程
    大自然搬运工
    转 curl命令
    HashMap扩容问题及了解散列均分
    mysql 分组查询并取出各个分组中时间最新的数据
    CNN 模型复杂度分析
    Attention机制
    深度学习之目标检测
  • 原文地址:https://www.cnblogs.com/chengmf/p/14890419.html
Copyright © 2011-2022 走看看