c – 如何在地图中插入结构?
发布时间:2020-12-16 10:45:57 所属栏目:百科 来源:网络整理
导读:删除给定行的注释后,我在代码中编译错误.我无法将结构插入到地图中,而插入整数很好.如何修复错误? # include iostream# include mapusing namespace std;struct node{int test;}temp;int main(){ temp.test = 24; int test = 30; map node,bool mymap1; map
删除给定行的注释后,我在代码中编译错误.我无法将结构插入到地图中,而插入整数很好.如何修复错误?
# 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; } 解决方法
std :: map的键内部存储在二叉搜索树中.为了在二叉搜索树中存储和搜索密钥,它们必须是可比较的.例如,二元搜索树的要求是左子项的键小于其父项的键,右子项的键大于其父项的键.但是,如果密钥不具有可比性,我们如何判断孩子是否比父母更大或更小?我们无法形成树,因此std :: map不适用于这些类型.
您只需要定义小于运算符,如下所示: bool operator<(const node& n1,const node& n2) { return n1.test < n2.test; } 如果“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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |