简体   繁体   中英

when vector<int> in unordered_map<int,vector<int>>.i cant change vector size,why?

unordered_map<int, vector<int>> map1;
vector<int> node_sum;
node_sum.push_back(10);
map1.insert(pair<int, vector<int>>(0, node_sum));
node_sum = map1.at(0);
node_sum.push_back(1);
node_sum.push_back(2);
cout <<"map1.at(0).size():"<< map1.at(0).size() << endl;
cout << "node_sum.size():" << node_sum.size()<< endl;

there will output:

map1.at(0).size():1 node_sum.size():3

why i cant change vector size

After map1.insert(pair<int, vector<int>>(0, node_sum)) , the map holds a copy of node_sum. node_sum and the object in the map are independent objects of the same type. You can see this by putting node_sum into a small scope and getting a reference to the object in the map. If you implement a test object with copy constructor, destructor etc that prints a message you can see what is going on in detail.

struct Foo {
    Foo() {cout << "Foo::Foo" << endl;}
    ~Foo() {cout << "Foo::~Foo" << endl;}
    Foo(Foo const& f) {cout << "Foo::Foo(const&)" << endl;}
    Foo& operator(Foo const& f) {cout << "operator=" << endl; return *this;}
};

int main() {
    {
        unordered_map<int, Foo> map1;
        {
            Foo foo;      
            map1.insert(make_pair(0, foo));
        }
        cout << "Will delete map1" << endl;
    }
    return 0;
}

node_sum = map1.at(0); probably does not what you think it should do. It returns a reference to the object in the map and then calls the assignment operator of std::vector on node_sum with the returned reference as parameter. This will copy the content of the object in the map into node_sum , but you still have two separate objects. Try

auto& map_node_sum = map1.at(0);
map_node_sum .push_back(1);
map_node_sum .push_back(2);
cout <<"map1.at(0).size():"<< map1.at(0).size() << endl;
cout << "map_node_sum .size():" << map_node_sum .size()<< endl;
cout << "node_sum.size():" << node_sum.size()<< endl;

You could also use return value of map::insert directly to save a query.

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