简体   繁体   中英

Using Functor to make a custom sort method in sets

I am trying to make a custom sorting method for set but the compiler doesn't run it. For example we are inserting the following numbers: 2 3 5 4 , set will sort them from the lowest value to the highest value, but what if I want it from the highest to the lowest? For : 2 3 5 4, instead of sorting them like this 2 3 4 5, I want 5 4 3 2. I wrote the following code:

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

using namespace std;

struct SortOrder {
    bool operator()(const int &first,const int &last) {
        if (first < last);
            return (first < last);
        return (first > last);
    }
};

int main(){
    set<int,SortOrder> date;
    set<int>::iterator it;
    date.insert(2);
    date.insert(3);
    date.insert(5);
    date.insert(4);
    for (it = date.begin(); it != date.end(); ++it) {
        cout << *it <<" ";
    }
    return 0;
}

Your implementation of comparator is incorrect, as deepmax has explained: your operator returns false only when the two items are equal to each other; in all other cases it returns true , effectively making it a "not equal" operator.

You don't have to write your own implementation, because C++ Standard Library provides an implementation for you:

set<int,std::greater<int>> date;

std::greater<int> is the comparator that you want ( demo ).

set<int,std::greater<int>> date {2, 3, 5, 4};
ostream_iterator<int> out_it (cout, " ");
copy (date.begin(), date.end(), out_it );

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