Key Requirements for std::map
In utilizing std::map, a common question arises regarding the characteristics a key class must possess to serve as a valid key.
The prerequisites are quite straightforward: the key class must provide copy and assignment capabilities. The actual ordering within the map is determined by the third template argument or the constructor argument (if specified). This argument typically defaults to std::less
To customize key ordering, you can create a comparison operator, ideally as a functional object. Here's an example of such an operator for a hypothetical type MyType:
struct CmpMyType { bool operator()(MyType const& lhs, MyType const& rhs) const { // Implementation of the comparison logic... } };
Note that this comparison operator must define a strict ordering. Specifically, if CmpMyType()(a, b) returns true, then CmpMyType()(b, a) must return false. If both expressions evaluate to false, the elements are considered equal and belong to the same equivalence class. By adhering to these requirements, you can extend the functionality of your key class to effectively serve as a valid key in std::map.
The above is the detailed content of What Key Requirements Must a Class Satisfy to Be Used as a Key in std::map?. For more information, please follow other related articles on the PHP Chinese website!