c++ - 对 map<> 使用自己的 Comparator operator()。如果找不到 KEY 则给出错误

标签 c++ dictionary struct operator-overloading

我尝试实现自己的运算符并在 map<> 中使用,代码如下:

#include <iostream>
#include <map>
#include <string>

using namespace std;

struct keyInfo
{
  string Key1; 
  string Key2; 

  /*bool keyInfo::operator()(keyInfo const& Left,keyInfo const& Right) const{
      return ((Left.Key1<Right.Key1)&&(Left.Key2<Right.Key2));
  }*/
};

struct LessComparer{
    bool operator()(keyInfo const& Left,keyInfo const& Right) const{
        return !(Left.Key1==Right.Key1 && Left.Key2==Right.Key2);
    }
};

struct valueInfo
{ 
  int value1; 
  int value2; 
  int value3; 

  valueInfo(const int A,const int B,const int C) : 
    value1(A),value2(B),value3(C) {}
};
typedef std::map<keyInfo, valueInfo, LessComparer> MapTYPE;

int main()
{
  MapTYPE TMap;
  keyInfo K;
  K.Key1="main";
  K.Key2="i";
  valueInfo V(-2,-3322,9000);

  TMap.insert(MapTYPE::value_type(K,V));
  MapTYPE::iterator It1=TMap.find(K);
  It1=TMap.find(K);
  if(It1!=TMap.end())
    std::cout<<"Success(K): "<<It1->second.value2<<std::endl;

  keyInfo E;
  E.Key1="main";
  E.Key2="j";
  //TMap.insert(std::pair<keyInfo,valueInfo>(E,V));
  MapTYPE::iterator It2=TMap.find(E);
  if (It2!=TMap.end())
     std::cout<<"Success(E): "<<(It2->second).value3<<std::endl;

  cin.get();
  return 0;
 }

这里我使用 operator() 返回 0 当且仅当 Left 和 Right 的 Key1 和 Key2 都相等。我认为这与 map::less 的工作方式相同,我的意思是它仅在满足相等条件时才返回 false。

它在第一种情况下工作正常,即 TMap.find(K) 找到相同的键。但是在第二种情况下调用期间,即 TMap.find(E) 它会弹出一条错误消息:

"Debug assertion failed"
Expression: Invalid operator <

最佳答案

比较运算符必须定义严格的弱排序。您通常可以通过词典比较为可比较类型的复合编写这样的比较:

define "(a1, b1) < (a2, b2)" if and only if

   (a1 < a2) OR (a1 == a2 AND b1 < b2)

这概括为任意元组 (a1, b1, c1, ...)以显而易见的方式。

在C++中,应该这样写:

return (Left.key1 < Right.key1) ||
       (!(Left.key1 > Right.key1) && (Left.key1 < Right.key1));

这样,您可以使用现有的 < 来定义任何类型元组的字典顺序。 - 每种成分类型的运算符。 (请注意,此排序认为两个元素 xy 等同于 !(x < y) && !(y < x)。)

关于c++ - 对 map<> 使用自己的 Comparator operator()。如果找不到 KEY 则给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9648100/

相关文章:

c++ - 在 dlopen 检测重复符号

使用 ARM 进行 C 编程 - 将结构输出和输入到文件

c++ - 错误 : default argument given for parameter 1

Python - 从 numpy 表创建字典以显示列表

python - 为什么 `dict_display` 允许重复键?

ios - 我收到信号 SIGABRT 和日志消息

c - 如何使用函数中的结构体指针访问结构体中的二维数组?

c - 简单的 list 。主文件中的规范(方法、结构)不会在单独的文件(h 和 c)中编译。为什么?

c++ - 图像处理 - 这是一个 for 循环问题吗?

python - 使用 C++ 或 Python 将表格 PDF 数据转换为文本(或任何其他可读格式)文件