質問

I'am receiving this weird error i have never seen it before and don't even know what it means, please give me a hand on it...

 #include<iostream>
    #include<map>
    #include<algorithm>
    using namespace std;
    class Person
{
  private:
   int code;
   string name;
  public:  
   Person(int cod,string nom);
   void setcode(int cod);
   void setname(string nom);
   int getcode();
   string getname();
};
    Person::Person(int cod,string nom){code=cod;name=nom;}
    void Person::setcode(int cod){code=cod;}
    void Person::setname(string nom){name=nom;}
    int Person::getcode(){return code;}
    string Person::getname(){return name;}

    int main ()
{
  map<Person,string>human;

  human.insert(make_pair(Person(15,"LewinVillar"),"primero"));
  human.insert(make_pair(Person(17,"GeanSosa"),"segundo"));
  human.insert(make_pair(Person(20,"WillyRamos"),"tercero"));
  human.insert(make_pair(Person(35,"WillyRojas"),"cuarto"));
  human.insert(make_pair(Person(40,"CuchoSalas"),"quinto"));

}

This is the error im getting

Error E2093 C:\Program Files (x86)\Borland\CBuilder6\Include\stl/_function_base.h 73: 'operator<' not implemented in type 'Person' for arguments of the same typ
const Person &,const Person &) const
役に立ちましたか?

解決

When you use a type as a key in a std::map, the map requires operator< to sort the elements it contains. You need to add:

friend inline bool operator<( const Person& lhs, const Person& rhs )
{
    return lhs.code < rhs.code;
}

(or something other appropriate) to your class. It could also be a free function after the class if you use the getters for code, there are several options.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top