Search code examples
c++sortingdictionarykey-value

Sort a map on the basis of first value of pair


Suppose I have to describe my map as:

map<int, pair<long, int>> mp;

Now I insert elements as:

int y; long x;
pair<long, int> p;

for(int i = 0; i < 5; i++)
{ 
    cin >> x >> y;
    p.first = x;
    p.second = y;
    mp.insert({i, p});   // What is wrong here syntax wise?
}

Further, I want to sort it on the basis of first value of the pair.


Solution

  • You can use a little trick here.

    Map in c++ automatically sorts everything by key, so you can do following =>

    map <long, (set,vector) < int > > mp; //Create this kind of map
    //it will sort elements by first value and depending on your needs, select vector or set
    //if you need to sort elements by second value use set
    //if you do not care about it use vector
    
    long x;
    int y;
    for (int i = 0; i < n; i++)
    {
       cin >> x >> y;
       if (mp.find(x) != mp.end()) // if element exist
          {
             mp[x].push_back(y); // add it to vector
          }
          else
          {
             mp[x] = vector < int > (); // if not create new vector
             mp[x].push_back(y); // and then push new element
          }
    }