简体   繁体   中英

Unable to use pair<int, int> as key in set in C++ STL

Set is a Sorted Associative Container that stores objects of type Key. Set is a Simple Associative Container, meaning that its value type, as well as its key type, is Key. It is also a Unique Associative Container, meaning that no two elements are the same.

I was trying to build a set<pair<int, int>> with the number and the position where it appears in the string as the key .

When trying to insert a pair<int, int> as the key for set , the insertion was not being successful when the first element of the pair appeared again although the pair was unique.

#include <iostream>
#include <set>
#include <iterator>

using namespace std;
struct compare
{
    bool operator()(const pair<int, int> &lhs, const pair<int, int> &rhs)
    {
        return lhs.first > rhs.first;
    }
};
void print(set<pair<int, int>, compare> myset)
{
    for(auto iter=myset.begin(); iter!=myset.end();++iter){
        cout << iter->first << ' ' << iter->second << endl;
    }
}

void BuildSet(int num)
{
    set<pair<int, int>, compare> values;
    string number = to_string(num);
    for(int i=0; i<number.size(); ++i)
    {
        int quot = number[i]-'0';
        values.insert(make_pair(quot, i));
    }
    cout << endl;
    print(values);
    cout << endl;
}
int main() {
    BuildSet(98738);
}

And the output was :

9 0
8 1
7 2
3 3

With the entry 8 4 missing as the first element was being duplicated.

The reason was very simple.

The compare method did know know how to handle in case the first element was already present in the 'set`. Modifying it to this resolved this problem.

struct compare
{
    bool operator()(const pair<int, int> &lhs, const pair<int, int> &rhs)
    {
         if(lhs.first != rhs.first)
         {
             return lhs.first > rhs.first;
         }
        else
        {
            return lhs.second > rhs.second;
        }
    }
};

Here, the first element of the pair is compared first and in case of equality the second element is checked as opposed to the earlier one when only the first element was compared.

You could use functor:

greater<pair<int, int>>()

or less<pair<int,int>>()

as cmp function. And #include<functional>

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