While declaring a set,
set <int, greater <int> > gquiz1;
why do we use greater <int>
? What purpose does it serve?
The std::greater is a functional object which is used for performing comparisons. It is defined as a Function object class for the greater-than inequality comparison. This can be used for changing the functionality of the given function.
Some basic functions associated with Set: begin() – Returns an iterator to the first element in the set. end() – Returns an iterator to the theoretical element that follows last element in the set. size() – Returns the number of elements in the set. max_size() – Returns the maximum number of elements that the set can hold.
operator= – The ‘=’ is an operator in C++ STL which copies (or moves) a set to another set and set::operator= is the corresponding operator function. get_allocator () – Returns the copy of the allocator object associated with the set. Recent Articles on set C++ Programming Language Tutorial | Set in C++ STL | GeeksforGeeks
Set in C++ Standard Template Library (STL) Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it.
std::set
is a container that contains an ordered set of objects.
The ordering of the objects is determined by the second argument. By default, it is std::less<Key>
. See the definition of std::set for additional details. However, you can override the default argument by using your own Compare
type as the second argument, as you have done in your posted code.
E.g.
std::set<int> set1; // Use default compare class, std::less<int>
set1.insert(10);
set1.insert(5);
set1.insert(7);
The order of the objects in the above container will be 5, 7, and 10. The objects in the container are sorted in increasing orer.
If you use
std::set<int, std::greater<int>> set2;
set2.insert(10);
set2.insert(5);
set2.insert(7);
The order of the objects in the above container will be 10, 7, and 5. The objects in the container are sorted in decreasing orer.
The declaration of std::set
looks like this:
template<
class Key,
class Compare = std::less<Key>,
class Allocator = std::allocator<Key>
> class set;
The entry goes on to say:
std::set
is an associative container that contains a sorted set of unique objects of type Key. Sorting is done using the key comparison function Compare.
By default, the key comparison is done using std::less
, meaning that the incoming entry is inserted at the first position where it is less than the item in the set that it's being compared against.
In your example, insertion is being performed using the std::greater
comparison, which will result in a set where the entries are sorted in an order opposite to the default case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With