小编ign*_*iks的帖子

如何在函数中返回 std::vector 的引用?

我假设向量的引用在 C++ 中无法正常工作。

例如,我将v的引用传递给change()并获取返回作为v的引用,返回的v与change()的输入不一样。这对我来说没有意义,因为我假设我们可以使用 & 进行引用调用,并将其作为对函数外的引用返回。

我用指针查看输入v和输出v的地址是否相同。但是,change() 制作了 v 的新副本并返回它,尽管我使用 & 将其作为引用返回。


如果我运行以下代码,v1 和 v2 不一样。

    #include <iostream>
    #include <vector>
    using std::cout;
    using std::endl;
    using std::vector;
    
    const vector<int>& const change(vector<int>& v) {
      v[1] = -1;             // change the elements in v
      return v;              // return a vector as reference
    }
    
    int main() {

      vector<int> v1 = {1, 2, 3, 4, 5};
      vector<int> v2 = change(v1);
    
      cout << &v1.at(0) << endl;  // check the address of v1
      cout << &v2.at(0) << …
Run Code Online (Sandbox Code Playgroud)

c++

1
推荐指数
1
解决办法
220
查看次数

标签 统计

c++ ×1