Using map with class error, compile error

有些话、适合烂在心里 提交于 2021-02-05 09:41:38

问题


I have the following compiler error, how could I fix it?

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> >]' 

This is the code:

#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;
 }

回答1:


For a std::map you need to have overloaded operator< on the Key type of the map, because that is how the map will insert elements into it's underlying container.

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
}

When overloading operator<, it's a good idea to in a similar fashion also overload operator>.




回答2:


You need a comparison function for the map. You can either create operator< that compares two instances of ar, or you can create a custom function and pass it as the 3rd template parameter.

An example of the former might be:

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



回答3:


operator < must be available for the key type, or you should provide a comparison functor to the map constructor.



来源:https://stackoverflow.com/questions/14967757/using-map-with-class-error-compile-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!