可能的重复:
如何返回对象"在 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.
这篇关于C++ 向量,返回与参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
读取输入文件,最快的方法?read input files, fastest way possible?(读取输入文件,最快的方法?)
在 C++ 中读取格式化输入的最简单方法?The easiest way to read formatted input in C++?(在 C++ 中读取格式化输入的最简单方法?)
从 .txt 文件读取到 C++ 中的二维数组Reading from .txt file into two dimensional array in c++(从 .txt 文件读取到 C++ 中的二维数组)
如何在 C++ 中模拟按键按下How to simulate a key press in C++(如何在 C++ 中模拟按键按下)
为什么在 cin.ignore() 之后没有 getline(cin, var) 读取Why doesn#39;t getline(cin, var) after cin.ignore() read the first character of the string?(为什么在 cin.ignore() 之后没有 getline(cin, var) 读取
scanf 格式输入的 cin 类比是什么?What is the cin analougus of scanf formatted input?(scanf 格式输入的 cin 类比是什么?)