如何在std :: map中使用struct?

New*_*bie 4 c++ stl stdmap

我有一个复杂的结构,我希望将其作为std :: map的一个关键字来快速生成所有唯一对象的列表:

union somecomplexstruct {
     struct {
        more_structs val1, val2;
        even_more_structs val3, val4;
        lots_of_more_structs val5;
     };
     unsigned int DATA[3];
};

typedef map<somecomplexstruct, int, greater<somecomplexstruct> > somecomplexstructMap;
Run Code Online (Sandbox Code Playgroud)

但它说错误: error C2784: 'bool std::operator >(const std::vector<_Ty,_Alloc> &,const std::vector<_Ty,_Alloc> &)' : could not deduce template argument for 'const std::vector<_Ty,_Alloc> &' from 'const somecomplexstruct'

我如何使我的结构在那里工作?

编辑:得到它的工作,感谢大家!下面是代码:

inline bool operator>(const somecomplexstruct &v1, const somecomplexstruct &v2){
    if(v1.DATA[0] > v2.DATA[0]) return 1;
    if(v1.DATA[0] < v2.DATA[0]) return 0;
    if(v1.DATA[1] > v2.DATA[1]) return 1;
    if(v1.DATA[1] < v2.DATA[1]) return 0;
    return v1.DATA[2] > v2.DATA[2];
}
Run Code Online (Sandbox Code Playgroud)

sbi*_*sbi 9

std::greater<>调用operator>()来完成它的工作,所以你需要重载它,如果你想使用它std::greater<>.

它应该如下所示:

inline bool operator>(const somecomplexstruct& lhs, const somecomplexstruct& rhs)
{
  // implement your ordering here. 
}
Run Code Online (Sandbox Code Playgroud)

  • @Newbie:`std :: map`使用排序来有效地确定它是否在地图中有给定的键.它通常作为平衡二叉搜索树实现.如果你不能提供订单,那么你可以提供一个哈希函数,并使用非标准的`boost :: unordered_map`或`hash_map`,如果你的C++实现提供它.如果你不能提供订单或哈希函数,那么你就无法有效地测试重复项,你也可以使用`vector <pair <Key,Value >>>并线性搜索它. (3认同)
  • @Newbie:最常见的订单生成方式是所谓的"词典订单".因此,如果struct X包含Y和Z,那么X的顺序函数就像`if(lhs.y <rhs.y)返回true; 如果rhs.y <lhs.y)返回false; return(lhs.z <rhs.z);`.您可以对具有多个成员的事物进行扩展,并且您必须为您关注的结构中包含的任何结构定义类似的顺序. (2认同)