In C++, you can utilize custom comparators with std::set
to control how elements are ordered and how duplicates are handled. This can be especially useful in performance-sensitive applications where the default ordering does not meet your requirements.
The following example demonstrates how to create a std::set
that uses a custom comparator to store integers and ensures that they are sorted in descending order.
#include <iostream>
#include <set>
// Custom comparator that sorts integers in descending order
struct DescendingComparator {
bool operator()(const int& lhs, const int& rhs) const {
return lhs > rhs; // Change the comparison to `>` for descending order
}
};
int main() {
std::set<int, DescendingComparator> mySet;
mySet.insert(5);
mySet.insert(3);
mySet.insert(8);
mySet.insert(1);
std::cout << "Elements in the set in descending order: " << std::endl;
for (const int& num : mySet) {
std::cout << num << " ";
}
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?