C++ STL 错误的键类型

标签 c++ stl types dictionary key

无法理解:g++ 编译器对:

lengths.insert(pair<Deux,long>(d,one));

在哪里

struct Deux {long big; long small};
map<Deux, long> lengths;
Deux d;
long one;

所以,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;

还使用结构节点:

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;
}*/

错误是:

    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*> >]()

最佳答案

编译器提示没有 operator <对于 Deux (我猜)。 key 必须是与 operator < 相当的类或者您必须将第三个模板参数传递给映射 - 比较器。

你看, map 以有序的方式保存它的键。为了对它们进行排序,它需要一个谓词。默认情况下,它会尝试使用 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;  
}

关于C++ STL 错误的键类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6595163/

相关文章:

c++ - visual studio 2010 包含文件可以是 'see' 但无法编译

c++ - 使用 pair with accumulate 的问题

c - 为什么从返回 int32_t 的函数返回 0x80000000 不会导致警告?

typescript - 有没有办法在 typescript 中为具有唯一项的数组定义类型?

java.lang.NumberFormatException : For input string: 异常

c++ - C++尝试针对每一帧将打印数据优化为二进制文件

c++ - 为什么包括原子 - 给出错误

c++ - RNG 崩溃的 C++ 程序

c++ - 如何通过 std::vector<T> 的子类的重载赋值运算符进行深度复制?

c++ - 为什么打印un_ordered map和map(dictionary)的key和value有异常?