#include <iostream>
#include <set>
class Person
{
public:
Person(const std::string& name, const std::size_t nld)
{
Name = name;
Nid = nld;
}
const std::string& GetName() const
{
return Name;
}
const void SetId()
{
Nid++;
}
const std::size_t GetId() const
{
return Nid;
}
private:
std::string Name;
std::size_t Nid;
};
//仿函数
struct PersonIdComparer: public std::binary_function<Person, Person, bool>
{
bool operator()(const Person& p1, const Person& p2) const
{
return (p1.GetId() < p2.GetId()) ? true : false;
}
};
struct PersonNameComparer: public std::binary_function<Person, Person, bool>
{
bool operator()(const Person& p1, const Person& p2) const
{
return (p1.GetName() < p2.GetName()) ? true : false;
}
};
int main()
{
const std::size_t nSize = 3;
const Person personArray[nSize] =
{
Person("Tom", 1),
Person("Jason", 2),
Person("Alice", 3)
};
std::set<Person,PersonIdComparer> ps1(personArray, personArray + nSize);
//插入元素
ps1.insert(Person("Bill",4));
//删除元素
std::set<Person, PersonIdComparer>::iterator it = ps1.begin();
std::advance(it, 1);
ps1.erase(it);
for(it = ps1.begin(); it != ps1.end(); ++it)
{
const_cast<Person&>(*it).SetId();
std::cout<<"Id:"<<(*it).GetId()<<"Name:"<<(*it).GetName()<<std::endl;
}
return 0;
}