C ++向量,返回与参数 [英] C++ vector, return vs. parameter

查看:108
本文介绍了C ++向量,返回与参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何返回一个对象 in 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).

如果使用现有的向量

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 ++向量,返回与参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆