通常,函数不应该有 vector 或其他标准库容器类型的形参。调用含有普通的非引用 vector 形参的函数将会复制 vector 的每一个元素。因此,调用含有普通的非引用vector作为形参的函数,无论效率还是资源利用率,都是极大的浪费。

从避免复制 vector 的角度出发,应考虑将形参声明为引用类型。但是,事实上,C++ 程序员倾向于通过传递指向容器中需要处理的元素的迭代器来传递容器:

考虑下面两个容器的传递:

#include<iostream>
#include<vector>

using namespace std;

void print_vector_pos(vector<int>::const_iterator beg,vector<int>::const_iterator end)
{
	while(beg!=end)
	{
		cout<<*beg++;
		if(beg!=end)
		{
			cout<<" ";
		}
	}
	cout<<endl;
}

void print_vector_copy(vector<int> coll)
{
	vector<int>::iterator pos;
	for(pos=coll.begin();pos!=coll.end();)
	{
		cout<<*pos++;
		if(pos!=coll.end())
		{
			cout<<" ";
		}
	}
	cout<<endl;
}

int main()
{
	int a[]={11,0,2,4,9,11,23,123,231,45,41,56};
	vector<int> coll(a,a+12);//coll(a[0],a[0]+5);//注意区别


	print_vector_copy(coll);

	print_vector_pos(coll.begin(),coll.end());

	system("pause");
	return 0;
}

直接传递迭代器肯定优于传递一个容器的副本。之前在做毕业设计时,就传递了容器作为形参,估计得改了。。

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐