C 如何使用对特定元素的引用来更改2Dvector的值

C++ How to change value of 2Dvector using reference to particular element?

本文关键字:引用 的值 2Dvector 元素 何使用      更新时间:2023-10-16

当我尝试更改向量时,我达到相同的值。请向我解释如何解决这个问题?

#include <iostream>
#include <vector>
using namespace std;
int &Give2DVectorRef(int i, int j, vector<vector<int>> &matrix) {
    return matrix.at(i).at(j);
}
int main() {
    vector<vector<int>> matrix{
        {1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}};
    int ref;
    ref = Give2DVectorRef(1, 3, matrix);
    ref = 55;
    cout << matrix.at(1).at(3) << endl; // print 2, but I expect 55
    return 0;
}

简短的答案是从

更改
int ref;
ref = Give2DVectorRef(1, 3, matrix);

to

int &ref = Give2DVectorRef(1, 3, matrix);

(如 @user1810087已经评论)

这里还有一些有关您的代码的评论

  • 对向量项目的引用可能很危险。

图像

 int & ref = Give2DVectorRef(1, 3, matrix); 
 matrix[1].erase(matrix[1].begin()+2); //deletes the third item
 ref = 55; // Reference is no longer meaningful 

如果您在参考项目的位置之前插入项目。

  • 不应将矩阵作为向量存储。如果您在大量的数值计算中使用此构造,则会面临严重的性能问题。长度(n*m)的单个向量将更快。

  • 的库的使用更好的是使用库。
  • 如果您担心性能,与操作员[]相比,操作员.at很慢。

  • 避免使用using namespace std;