我无法理解以下行为。当我使用currPMap修改值时,实际位置的值不会被修改。为什么呢。

我检查了operator[]at()返回引用的引用,因此应该可以使用。

#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;
}

输出:
0
3

附注:我知道我在这里所做的事情可以通过许多其他方式在这种情况下实现,但这不是实际的程序。这只是我的代码所面临的问题的显式版本。如果有人回答这种方法有什么问题,我将不胜感激。

最佳答案

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

那不是别名(又名引用);那是副本。如果要引用,则需要这样声明:
map<int, intMap> & currPMap = b.at(curr);
                 ^

请注意,如果您向 vector 添加或删除元素,则引用可能会无效,因为 vector 需要移动其元素以维持连续数组。

10-07 19:52
查看更多