How do I customize hashing and equality with std::multiset?

In C++, `std::multiset` allows you to store multiple values in a sorted manner. By default, it uses the `std::less` comparator for ordering and the default equality operator for determining equality. However, you can customize both hashing and equality using a combination of templates and functors.

Here's an example of how to define your own hash function and equality comparison for a custom type, which you can then use with `std::multiset`.

#include <iostream> #include <set> #include <string> // Custom struct struct Person { std::string name; int age; // Constructor Person(std::string name, int age) : name(name), age(age) {} // Less-than operator for ordering bool operator<(const Person& other) const { return name < other.name; } // Equality operator bool operator==(const Person& other) const { return name == other.name && age == other.age; } }; // Custom comparator struct PersonComparator { bool operator()(const Person& lhs, const Person& rhs) const { return lhs.name < rhs.name; // You can extend this for more complex comparison } }; int main() { std::multiset people; people.insert(Person("Alice", 30)); people.insert(Person("Bob", 25)); people.insert(Person("Alice", 22)); // Duplicate by custom logic for (const auto& p : people) { std::cout << p.name << " is " << p.age << " years old" << std::endl; } return 0; }

C++ std::multiset custom hashing custom equality functors C++ standard library