如何在地图中插入结构?

Bha*_*tan 3 c++ struct dictionary insert stdmap

删除给定行的注释后,我在代码中编译错误.我无法将结构插入到地图中,而插入整数很好.如何修复错误?

# include <iostream>
# include <map>

using namespace std;

struct node
{int test;} temp;

int main()
{
    temp.test = 24;
    int test = 30;
    map<node, bool> mymap1;
    map<int, bool> mymap2;
    //mymap1.insert(make_pair(temp, true));
    mymap2.insert(make_pair(test, true));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Ern*_*ill 11

对于作为地图关键字的类型,必须进行排序.实际上,所有这些意味着operator<必须为该类型定义.如果你定义了一个全局operator<(const node&, const node&),这应该工作正常; 即

bool operator<(const node& n1, const node& n2) {
    return n1.test < n2.test;
}
Run Code Online (Sandbox Code Playgroud)


And*_*sen 8

std :: map的键内部存储在二叉搜索树中.为了在二叉搜索树中存储和搜索密钥,它们必须是可比较的.例如,二元搜索树的要求是左子项的键小于其父项的键,右子项的键大于其父项的键.但是,如果密钥不具有可比性,我们如何判断孩子是否比父母更大或更小?我们无法形成树,因此std :: map不适用于这些类型.

您只需要定义小于运算符,如下所示:

bool operator<(const node& n1, const node& n2)
{
    return n1.test < n2.test;
}
Run Code Online (Sandbox Code Playgroud)

如果"test"数据成员是私有的,那么它也必须是节点结构的朋友(因为节点当前是结构,所以它现在是公共的).但是,我可能会这样做:

#include <map>

class node
{
    public:
        int getTest() const { return _test; }
        void setTest(int test) { _test = test; }
    private:
        int _test;
};

bool operator<(const node& n1, const node& n2)
{
    return n1.getTest() < n2.getTest();
}

int main()
{
    std::map<node,bool> foo;
    node n;
    n.setTest(25);

    foo[n] = true;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)