Using map with class error, compile error

后端 未结 3 1914
自闭症患者
自闭症患者 2021-01-28 02:49

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

error:  instantiated from `_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&a         


        
相关标签:
3条回答
  • 2021-01-28 03:20

    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>.

    0 讨论(0)
  • 2021-01-28 03:30

    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);
      }
      ...
    };
    
    0 讨论(0)
  • 2021-01-28 03:31

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

    0 讨论(0)
提交回复
热议问题