void
void

Reputation: 386

set<pair<K, V> > with greater functor by default

I have map <string,int> where I have to sort map on value. I have dumped map elements in a set<pair<K, V> > where I got all the element in less than order as set is constructed with a less functor. So is there any way I insert element in a set with greater functor.

Upvotes: 2

Views: 6634

Answers (2)

juanchopanza
juanchopanza

Reputation: 227390

You can use std::set's 2nd template parameter with std::greater<Key> instead of the default std::less<Key>.

std::set<Foo, std::greater<Foo>> s;

Here's a working example:

#include <set>
#include <functional>
#include <iostream>

int main()
{
  std::set<int> a{4,2,8,6,4};
  std::set<int, std::greater<int>> b(a.begin(), a.end());

  for (auto i : a) std::cout << i << " ";
  std::cout << '\n';

  for (auto i : b) std::cout << i << " ";
  std::cout << '\n';
}

Output:

2 4 6 8 
8 6 4 2 

Upvotes: 2

Barry
Barry

Reputation: 302852

As you can see in this reference, std::set is defined as:

template<
    class Key,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<Key>
> class set;

To sort in a different order, we simply have to provide a different Compare, in this case:

std::set<std::pair<K,V>, std::greater<std::pair<K,V> > mySet;

But if you already have a std::map with the objects in them, std::map also allows for a different comparator:

template<
    class Key,
    class T,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<std::pair<const Key, T> >
> class map;

If you wanted to sort in decreasing order by K, rather than copy all your elements into a set, you could have just started with:

std::map<K, V, std::greater<K> > myDecreasingOrderedMap;

Upvotes: 4

Related Questions