class Person {
private:
int m_age;
std::string m_name;
public:
Person(int a, std::string b) : m_age(a), m_name(std::move(b)) {}
int age() const { return m_age; }
const std::string& name() const { return m_name; }
void print() const { std::cout << "age:" << m_age << " name:" << m_name << std::endl; }
};
struct CompareAge
{
template<typename T>
bool operator() (const T &t1, const T &t2) const
{
return t1.age() < t2.age();
}
};
struct CompareName
{
template<typename T>
bool operator() (const T &t1, const T &t2) const
{
return t1.name() < t2.name();
}
};
int main()
{
Person a(15, "abcd");
Person b(25, "babcd");
Person c(17, "cendaf");
std::set<Person, CompareAge> e;
e.insert(a);
e.insert(b);
e.insert(c);
for ( auto &v : e)
{
v.print(); // 如果函数不加const 则不能访问
}
std::cout << std::endl;
std::set<Person, CompareName> g;
g.insert(a);
g.insert(b);
g.insert(c);
for (auto &v : g)
{
v.print();
}
std::cout << std::endl;
Person aa(25, "abcd");
auto it = g.find(aa);
if (it != g.end())
{
it->print();// 出来的结果 15,abcd 说明是可以查找成功,这是按字母大小来查找,所以25无关,这个需要注意
}
}