C 如何使用对特定元素的引用来更改2Dvector的值
C++ How to change value of 2Dvector using reference to particular element?
当我尝试更改向量时,我达到相同的值。请向我解释如何解决这个问题?
#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;
相关文章:
- 为什么在我的函数类型后使用引用运算符 (&) 允许我修改它返回的值?
- C++重新引用向量中的值
- 类型为 "Bucket&"(未限定的 const 限定)的引用不能使用 "SortedList." 类型的值进行初始化 如何修复此错误?
- 修改在 std::future 的 lambda 中引用捕获的值
- 为什么通过 vector<reference_wrapper> 的元素删除引用的值<T>不会使向量无效?
- C++ 按引用或值推送的并发队列
- C++对象引用返回不同的值
- 对象引用中的字段以不同的方法返回不同的值
- 返回 std::tuple 中的引用和值
- 具有对象的右值引用的线程
- 如何在C++中使用 void* 在指针作为对方法的引用传递时保存uint32_t的值
- 使用 sscanf 设置结构引用的值
- 修改右值引用的值 - 它是如何工作的
- 指针引用的值不再存在时输出冲突
- 更改对函数中静态变量的引用的值
- 引用数据类型的 & 符号是否返回引用本身的地址或它所引用的值
- 如何使用C++编译器/链接器/技巧来检测已分配但以后从未引用的值
- 更好的std::在指针集合上查找,并将取消引用的值与常量引用值进行比较
- 按赋给const引用的值返回
- 在c++中,当我将引用的值赋给对象时会发生什么?