C++ 向量,返回与参数
可能的重复:
如何返回对象"在 C++ 中
我想知道以下三种方法是否有区别:
I am wondering if there is a difference between the three following approaches:
void FillVector_1(vector<int>& v) {
v.push_back(1); // lots of push_backs!
}
vector<int> FillVector_2() {
vector<int> v;
v.push_back(1); // lots of push_backs!
return v;
}
vector<int> FillVector_3() {
int tab[SZ] = { 1, 2, 3, /*...*/ };
return vector<int>(tab, tab + SZ);
}
推荐答案
最大的区别是第一种方式是附加到现有内容,而另外两种方式填充一个空向量.:)
The biggest difference is that the first way appends to existing contents, whereas the other two fill an empty vector. :)
我觉得你要找的关键词是返回值优化,应该比较常见(使用 G++ 你必须专门关闭它以防止它被应用).也就是说,如果用法是这样的:
I think the keyword you are looking for is return value optimization, which should be rather common (with G++ you'll have to turn it off specifically to prevent it from being applied). That is, if the usage is like:
vector<int> vec = fill_vector();
那么可能很容易没有副本(而且该功能更易于使用).
then there might quite easily be no copies made (and the function is just easier to use).
如果您正在使用现有向量
If you are working with an existing vector
vector<int> vec;
while (something)
{
vec = fill_vector();
//do things
}
然后使用 out 参数将避免在循环中创建向量和复制数据.
then using an out parameter would avoid creation of vectors in a loop and copying data around.
相关文章