【问题标题】:Using map with class error, compile error使用带有类错误的地图,编译错误
【发布时间】:2024-01-20 10:45:01
【问题描述】:

我有以下编译器错误,我该如何解决?

error:  instantiated from `_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = ar, _Tp = int, _Compare = std::less<ar>, _Alloc = std::allocator<std::pair<const ar, int> >]' 

这是代码:

#include <map>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstdlib>

using namespace std; 

class ar { 
  public:
  int a;
  int b;
  int c;
public:
  ar() : a(0), b(0), c(0) {}
};

int main() {
   map<ar, int> mapa;
   ar k;
   k.a = 6;
   k.b = 1;
   k.c = 0;
   mapa[k] = 1;

   //system("pause");
   return 0;
 }

【问题讨论】:

标签: c++ class map compilation


【解决方案1】:

对于 std::map,您需要在地图的 Key 类型上重载 operator&lt;,因为这是地图将元素插入其底层容器的方式。

class ar { 
  public:
  int a;
  int b;
  int c;
  public:
  ar() : a(0), b(0), c(0) {}
  bool operator<(const ar& other) const;
  };

bool ar::operator< (const ar& other) const // note the function has to be const!!!
{
   return (other.a < a) && (other.b < b) && (other.c < c); // or some such ordering
}

当重载operator&lt; 时,最好以类似的方式重载operator&gt;

【讨论】:

  • 我仍然遇到同样的错误。会不会是另一个问题?
  • operator&lt; 必须是 const 函数。然后it works
【解决方案2】:

您需要map 的比较函数。您可以创建 operator&lt; 来比较 ar 的两个实例,也可以创建自定义函数并将其作为第三个模板参数传递。

前者的一个例子可能是:

class ar {
  ...
  bool operator<(const ar& rhs) const {
    return std::tie(a,b,c) < std::tie(rhs.a, rhs.b, rhs.c);
  }
  ...
};

【讨论】:

  • 为什么在这种情况下具有比较功能很重要?在这种情况下,我唯一的愿望是我的班级代表地图的索引。
  • @user2085124 因为地图在其底层容器中对其元素进行排序,如果它不知道 如何 对它们进行排序,则无法执行此操作。它依赖于 Key 类型中存在的一些比较函数。
  • 我仍然遇到同样的错误。会不会是另一个问题?
  • @user2085124 - 我的代码中有一个错误,我已经在我的答案中修复了这个错误。注意函数签名更改为const。现在是works for me
  • 为什么必须是 const?
【解决方案3】:

operator &lt; 必须可用于键类型,或者您应该为映射构造函数提供比较函子。

【讨论】:

    最近更新 更多