C++ vector, return vs. parameter(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.
这篇关于C++ 向量,返回与参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 向量,返回与参数
基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
