当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - overloading operator() for set

问题描述:

Here,in the below code i do not understand why the custom structre has been created and How the overloaded operator() works.It would be a great help for me if someone help me out.

Here in the code i tried to insert the custom data type in the set.

#include<iostream>

#include<set>

#include<string>

using namespace std;

class Person

{

public:

string name;

int id;

Person()

{

}

Person(int id, string name)

{

this->id = id;

this->name = name;

}

void print() const

{

cout<<"ID : "<<id <<" Name: "<<name<<endl;

}

bool operator < (const Person& P) const

{ ///cout<<this->id<<" "<<P.id<<endl;

if (this->id > P.id)

return true;

return false;

}

bool operator == (const Person& P) const

{

if (this->id == P.id)

return true;

return false;

}

};

struct custom

{

bool operator () (const Person& left,const Person& right) const

{

if(right < left)

{

if (right == left)

return true;

return true;

}

return false;

}

};

int main()

{

set<Person,custom> s;

s.insert(Person(5,string("G")));

s.insert(Person(1,string("A")));

s.insert(Person(1,string("A")));

s.insert(Person(2,string("B")));

s.insert(Person(2,string("B")));

s.insert(Person(3,string("C")));

s.insert(Person(4,string("D")));

s.insert(Person(4,string("D")));

set<Person> :: iterator it = s.begin();

while(it != s.end())

{

it->print();

it++;

}

}

}

网友答案:

set<Person> would use Person::operator< to compare objects when adding to the set or searching for an element. set<Person, custom> uses custom::operator() to compare objects. In this code, custom::operator() effectively returns right < left (if you read through all the redundant and misleading code), so set<Person, custom> creates a set whose order is the opposite of the set created by set<Person>.

Note that the body of Person::operator<(const Person& P) could be written much more simply as return id > P.id;, and the body of custom::operator(), as I mentioned above, is simply right < left.

分享给朋友:
您可能感兴趣的文章:
随机阅读: