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;
}
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?