How can I use std::maps with user-defined types as key?

前端 未结 7 1688
灰色年华
灰色年华 2020-11-22 04:30

I\'m wondering why I can\'t use STL maps with user-defined classes. When I compile the code below, I get the following cryptic error message. What does it mean? Also, why is

相关标签:
7条回答
  • 2020-11-22 05:17

    The right solution is to Specialize std::less for your class/Struct.

    • Basically maps in cpp are implemented as Binary Search Trees.

    1. BSTs compare elements of nodes to determine the organization of the tree.
    2. Nodes who's element compares less than that of the parent node are placed on the left of the parent and nodes whose elements compare greater than the parent nodes element are placed on the right. i.e.

    For each node, node.left.key < node.key < node.right.key

    Every node in the BST contains Elements and in case of maps its KEY and a value, And keys are supposed to be ordered. More About Map implementation : The Map data Type.

    In case of cpp maps , keys are the elements of the nodes and values does not take part in the organization of the tree its just a supplementary data .

    So It means keys should be compatible with std::less or operator< so that they can be organized. Please check map parameters.

    Else if you are using user defined data type as keys then need to give meaning full comparison semantics for that data type.

    Solution : Specialize std::less:

    The third parameter in map template is optional and it is std::less which will delegate to operator< ,

    So create a new std::less for your user defined data type. Now this new std::less will be picked by std::map by default.

    namespace std
    {
        template<> struct  less<MyClass>
        {
            bool operator() (const MyClass& lhs, const MyClass& rhs) const
            {
                return lhs.anyMemen < rhs.age;
            }
        };
    
    }
    

    Note: You need to create specialized std::less for every user defined data type(if you want to use that data type as key for cpp maps).

    Bad Solution: Overloading operator< for your user defined data type. This solution will also work but its very bad as operator < will be overloaded universally for your data type/class. which is undesirable in client scenarios.

    Please check answer Pavel Minaev's answer

    0 讨论(0)
提交回复
热议问题