STL map 的一个问题

先看看这个代码

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

using namespace std;

int main() {
    map<int, vector<int> > map_a, map_b;
    map_a[0].push_back(0);
    map_b[0] = map_a[0];
    map_b[0].push_back(0);
    cout<<map_a[0].size()<<endl;
    return 0;
}

会输出 1 还是 2 呢,如果按照 map 存 vector 的引用来理解,应该是输出 2 的。

而实际是输出 1 的。

看看这个

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

using namespace std;

int main() {
    map<int, vector<int> > map_a, map_b;
    map_a[0].push_back(0);
    cout<<&map_a[0]<<endl;
    map_b[0] = map_a[0];
    cout<<&map_b[0]<<endl;
    map_b[0].push_back(0);
    cout<<&map_b[0]<<endl;
    cout<<map_a[0].size()<<endl;
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *