简体   繁体   中英

insertion in unordered map in c++

#include<iostream>
#include<unordered_map>
#include<list>
#include<cstring>

using namespace std;
class Graph {
    unordered_map<string, list<pair<string, int>>>l;
public:
    void addedge(string x, string y, bool bidir, int wt) {
        l[x].push_back(make_pair(y, wt));
        if (bidir) {
            l[y].push_back(make_pair(x, wt));
        }
    }
};

int main()
{
    Graph g;
    g.addedge("A", "B", true, 20);
    return 0;
}

unordered map in c++ dont uses push_back() function for insertion then how this unordered map 'l' is using push_back() function.

When you use the subscript operator on l , like in l[x] , it returns a reference to the value mapped to the key x (or inserts a default constructed value and returns a reference to that).

In this case, the type of the value is a std::list<std::pair<std::string, int>> and that type has a push_back member function.

It's the same as this:

std::list<std::pair<std::string, int>>& listref = l[x];
listref.push_back(make_pair(y, wt));

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