C++ STL错误的键类型

gau*_*inc 1 c++ types stl key map

无法理解这一点:g ++编译器很生气:

lengths.insert(pair<Deux,long>(d,one));
Run Code Online (Sandbox Code Playgroud)

哪里

struct Deux {long big; long small};
map<Deux, long> lengths;
Deux d;
long one;
Run Code Online (Sandbox Code Playgroud)

所以,g ++说,我想念operator<.使重载后operator<struct Deux,我看到了新的有趣的,但同样的错误:

map <long, Node*>ArrayOfNodes;
map <long, Node*>::iterator it;  
  for (it=ArrayOfNodes[Root]->nodes.begin();it<ArrayOfNodes[Root]->nodes.end();++it)
      cout<<it->first<<endl;
Run Code Online (Sandbox Code Playgroud)

还使用了结构节点:

struct Node {
   long name;
   long guest;
   map <long,Node*>nodes;
/*bool operator<(const Node& node)const{
 if ((*this).name<node.name) return true;
 if ((*this).name>node.name) return false;
  return (*this).guest<(*this).guest;
}*/
Run Code Online (Sandbox Code Playgroud)

和错误是:

    no match for operator< in it < ((Path*)this)->Path::ArrayOfNodes.
 std::map<_Key, _Tp, _Compare, _Alloc>::operator[] [with _Key = long int, _Tp = Node*,
 _Compare = std::less<long int>, _Alloc = std::allocator<std::pair<const long int, Node*> >]
 (((const long int&)((const long int*)(&((Path*)this)->Path::Root))))->Node::nodes.std::map<_Key, _Tp, _Compare, _Alloc>::end 
 [with _Key = long int, _Tp = Node*, _Compare = std::less<long int>, _Alloc = std::allocator<std::pair<const long int, Node*> >]()
Run Code Online (Sandbox Code Playgroud)

Arm*_*yan 6

编译器会抱怨,没有operator <Deux(我猜).键必须是一个类似的类operator <或者你必须传递第三个模板参数来映射 - 比较器.

你看,地图按顺序保存其键.为了订购它们,它需要一个谓词.默认情况下它会尝试使用operator <

尝试写这样的东西:

bool operator < (Deux const & d1, Deux const & d2)
{
   if(d1.big > d2.big)
      return false;
   if(d1.big < d2.big)
     return true;
   return d1.small < d2.small;  
}
Run Code Online (Sandbox Code Playgroud)

  • @loldop:我认为我的版本更正确,因为它处理大的时候相同的情况 (2认同)