简体   繁体   English

如何修改向量向量的元素(使用自动迭代器)?

[英]How can I modify elements of a vector of vectors (with auto iterator)?

I'm new to the STL (I'm not a professional coder aswell) and I'm having problems trying to modify the elements of a Matrix with the auto iterator... I've tried many different ways (also with references as you can see) but I'm still not able to put hands on the data.我是 STL 的新手(我也不是专业的编码员),我在尝试使用自动迭代器修改 Matrix 的元素时遇到问题......我尝试了许多不同的方法(也参考为你可以看到)但我仍然无法掌握数据。 The code below is what I'm trying to do...下面的代码是我正在尝试做的......

for (auto & e : D.getMat())
{
    for (auto & i : e)
    {
        i = 3;
    }
}

D is an object of my class "Matrix" and getMat is: D 是我的 class “矩阵”的 object,getMat 是:

vector<vector<int>> getMat();

And here it's what it does:这就是它的作用:

vector<vector<int>> Matrix::getMat()
{
    return _mat;
}

_mat is private and declared as: _mat 是私有的并声明为:

vector<vector<int>> _mat;

Please forgive my ignorance but I'm moving my first steps in this world.请原谅我的无知,但我正在这个世界上迈出第一步。

getMat() returns by value, so it returns a copy of the data member _mat , and any modification on the copy has nothing to do with the original _mat . getMat()按值返回,因此它返回数据成员_mat的副本,对副本的任何修改都与原始_mat

Change it to return-by-reference.将其更改为按引用返回。 eg例如

vector<vector<int>>& Matrix::getMat()
//                 ^
{
    return _mat;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM