-1

Why is my code giving a compilation error?

I want to have a multiset that can contain 3 items in a sorted order of the first item, if there is a tie then the second item, if there is again a tie then the third item.

Please suggest me a solution or any other data structure.

int main()
{
    int n;
    cin >> n ; 
    multiset<int, pair<int, int>> m;

    for(int i = 0 ; i < n ;i++)
    {
        int a, b, c ;
        cin >> a >> b >> c; 
        pair<int, int> p1 = make_pair(b, c) ;  
        pair<int, pair<int, int>> p2 = make_pair(a, p1) ; 
        m.insert(p2)  ; 
    }

    for(auto it = m.begin() ; it != m.end() ;it++)
    {
        cout << it->first << " " << it->second.first << " " << it->second.second << endl;
    }

    return 0;
}
halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

2

Why is my code giving a compilation error?

You are getting a compilation error is because multiset only accept a single template for data type. The second template parameter is for a comparison function, which pair<int, int> is definitely not one.

I want to have a multiset which can contain 3 items and in a sorted order of first item, if there is a tie then second item, if there is again tie then third item.

What you are looking for is std::multiset<std::tuple<int, int, int>>.

Just like pair, tuple would compare the first data, and if the first data ties, it goes to the second data, and so on. In fact, pair is a specific case of tuple with only 2 elements.

Do note that to access data in a tuple, you can't use tuple.first or tuple.second, instead you have to use std::get<INDEX>(your_tuple). Also since INDEX here is a compile time variable, so you can not use a for loop to access elements of a tuple like an array.

halfer
  • 19,824
  • 17
  • 99
  • 186
Ranoiaetep
  • 5,872
  • 1
  • 14
  • 39