Home >Backend Development >C++ >How Can I Use User-Defined Types as Keys in C std::maps?
In C programming, the use of STL maps with user-defined classes often encounters cryptic compiler errors. Specifically, the error message "no match for 'operator<' in '__x < __y'" is common when attempting to access an element using a key of a user-defined type.
The error message suggests that the compiler is unable to find the operator < for comparing two instances of the user-defined type. This is because, by default, STL maps require a comparison operator (operator<) to order their keys. However, when working with user-defined types, this operator is not automatically available.
Instead of defining operator< for a user-defined type, one can create a comparator function object class. This class implements a specialized version of operator() that determines the relative ordering of the user-defined type. The map can then be specialized to use this comparator:
struct Class1Compare { bool operator() (const Class1& lhs, const Class1& rhs) const { return lhs.id < rhs.id; } }; std::map<Class1, int, Class1Compare> c2int;</p> <h3>Solution 2: Specializing std::less</h3> <p>Another alternative is to specialize the std::less template for the user-defined type. This provides a custom definition for operator() within the std::less class:</p> <pre class="brush:php;toolbar:false">namespace std { template<> struct less<Class1> { bool operator() (const Class1& lhs, const Class1& rhs) const { return lhs.id < rhs.id; } }; }
This approach allows the map to default to std::less for comparison, while providing a specific implementation for the user-defined type.
When working with STL maps and user-defined types, it is essential to provide a method for comparing the keys. This can be achieved either through a comparator function object or by specializing std::less. By addressing this requirement, developers can effectively utilize maps with user-defined types as keys.
The above is the detailed content of How Can I Use User-Defined Types as Keys in C std::maps?. For more information, please follow other related articles on the PHP Chinese website!