简体   繁体   中英

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. 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:

vector<vector<int>> getMat();

And here it's what it does:

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

_mat is private and declared as:

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 .

Change it to return-by-reference. eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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