mkostya
mkostya

Reputation: 972

Initializing set with comparator in C++

I encountered the following code:

#include <iostream>
#include <set>

int main() {

   auto comp = [](int x, int y){return (x > y); };

   std::set<int, decltype(comp)> inversed({1,2,3,4,5}, comp);
   for ( auto i = inversed.begin(); i != inversed.end(); ++i ) {
      std::cout << *i << std::endl;
   }

   return 0;
}

The code prints "5 4 3 2 1", i.e initial set in inversed order. Can anybody explain why? How comparator influences initialization of the set?

Thanks,
Kostya

Upvotes: 2

Views: 481

Answers (2)

Paolo M
Paolo M

Reputation: 12757

When defining comp, you are defining the order function for your set. For your set, two elements will be ordered if its order function will be fulfilled.

So, being std::set an ordered container, you get that result, i.e. inversed store its elements sorted, but the order is descending because it's the order defined by comp.

Upvotes: 3

SingerOfTheFall
SingerOfTheFall

Reputation: 29966

An std::set uses a comparator to determine the order of elements. The default semantics for a comparator is "less", which means that if running a comparator on two values (A,B) returns true, then A should be placed before B.

In your case, the comparator does the opposite (returns true if A is "greater" than B), that's why bigger elements appear in front of the smaller ones.

Upvotes: 5

Related Questions