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次拷贝
原文地址:https://www.cnblogs.com/chengmf/p/14890419.html