c++代码中的运行时错误

Run Time Error in a C++ code

本文关键字:运行时错误 代码 c++      更新时间:2023-10-16

我在c++代码中得到运行时错误。我给我的源代码错误信息。需要帮助!提前谢谢。

源代码:

#include <map>
#include <cstdio>
using namespace std;
class Pair{
    public:
    int x;
    int y;
};
map < Pair , int > mapper;
int main(){
    Pair a;
    a.x = 8;
    a.y = 9;
    mapper[a] = 1; // Here i get Run-Time-Error
    return 0;
}

错误信息:

c:program filescodeblocksmingwbin..libgccmingw324.7.1includec++bitsstl_function.h|237|note:   'const Pair' is not derived from 'const std::multimap<_Key, _Tp, _Compare, _Alloc>'|

错误在于必须定义一个方法来提供pair之间的排序。Map不知道如何比较对象

一个例子:

#include <map>
#include <cstdio>
using namespace std;
class Pair{
public:
  int x;
  int y;
};
bool operator<(const Pair& l, const Pair& r) {
  return l.x < r.x;
}

map < Pair , int > mapper;
int main(){
  Pair a;
  a.x = 8;
  a.y = 9;
  mapper[a] = 1;
  return 0;
}

在本例中,使用x的值比较pair,但是您可以根据需要提供一个函数。