简体   繁体   中英

alias used not modifying the actual contents of STL container

I am unable to understand the following behaviour. When I use currPMap to modify the value, the value at the actual location is not modified. Why is that so.

I checked with the reference the operator[] and at() return reference and so this should have worked.

#include <iostream>
#include <vector>
#include <map>

using namespace std;

typedef map<int, int> intMap;
typedef map<int, int>::iterator mapIt;

int main(void) {
    vector< map<int, intMap > > b(2);
    int curr=0, next=1;
    map<int, intMap> currPMap = b.at(curr);
    (currPMap[4])[2] = 3;    //modified by currPMap.
    cout<<((b.at(curr))[4])[2]<<endl;
    ((b.at(curr))[4])[2] = 3;    //modified using the actual vector.
    cout<<((b.at(curr))[4])[2]<<endl;
}

Output:

0
3

PS: I know what I am doing here can be achieved by many other ways in this setting, but this is not the actual program. This is just the explicit version of the problem that I am facing with my code. I would be grateful if someone answers what is wrong in this method.

Because you are getting a copy of a map here, not an alias :

map<int, intMap> currPMap = b.at(curr); // currMap is a copy of b[0]

You then modify the copy, not the map stored in the vector.

What you need is a reference:

map<int, intMap>& currPMap = b.at(curr); // currMap refers to b[0]
map<int, intMap> currPMap = b.at(curr);

That's not an alias (aka reference); that's a copy. If you want a reference, you need to declare it thusly:

map<int, intMap> & currPMap = b.at(curr);
                 ^

Beware that the reference may be invalidated if you add or remove elements to the vector, since vectors need to move their elements to maintain a contiguous array.

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