Home > Blockchain >  insertion in unordered map in c
insertion in unordered map in c

Time:07-04

#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.

CodePudding user response:

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));
  • Related