重载了<和==
#include <iostream>
#include <cstdlib>
#include <deque>
#include <functional>
#include <algorithm>
#include <numeric>
using namespace std;
class Cat
{
public:
Cat(int age)
{
this->age = age;
}
private:
int age;
public:
bool operator<(Cat& c)const
{
return this->age < c.age;
}
bool operator==(int age)const
{
return this->age == age;
}
int getAge()
{
return this->age;
}
};
int main()
{
deque<Cat> catDeq;
for (int i = 1; i != 10; ++i)catDeq.push_back(Cat(i));
for (int i = 1; i != 5; ++i)catDeq.push_back(Cat(i));
for (int i = 2; i != 6; ++i)catDeq.push_back(Cat(i));
catDeq.push_back(Cat(9));
catDeq.push_back(Cat(9));
deque<Cat>::iterator iter;
iter = max_element(catDeq.begin(), catDeq.end());
cout << "年龄最大的猫咪的年龄是:" << (*iter).getAge() << endl;
cout << "一共有 " << count(catDeq.begin(), catDeq.end(), (*iter).getAge()) << " 只" << endl;
for (int max = (*iter).getAge(), cnt = 0; iter != catDeq.end(); ++iter)
{
iter = max_element(iter, catDeq.end());
if (max == (*iter).getAge())
{
cout << "第" << ++cnt << "只猫咪的序号是:" << distance(catDeq.begin(), iter) << " (从0开始)" << endl;
}
else
{
break;
}
}
iter = min_element(catDeq.begin(), catDeq.end());
cout << "年龄最小的猫咪的年龄是:" << (*iter).getAge() << endl;
cout << "一共有 " << count(catDeq.begin(), catDeq.end(), (*iter).getAge()) << " 只" << endl;
for (int max = (*iter).getAge(), cnt = 0; iter != catDeq.end(); ++iter)
{
iter = min_element(iter, catDeq.end());
if (max == (*iter).getAge())
{
cout << "第" << ++cnt << "只猫咪的序号是:" << distance(catDeq.begin(), iter) << " (从0开始)" << endl;
}
else
{
break;
}
}
pair< deque<Cat>::iterator, deque<Cat>::iterator> resultPair = minmax_element(catDeq.begin(), catDeq.end());
cout << "年龄最小的猫咪的年龄是:" << (*resultPair.first).getAge() << endl;
cout << "一共出现了 " << count(catDeq.begin(), catDeq.end(), (*resultPair.first).getAge()) << " 次" << endl;
cout << "其中一只出现的位置是:" << distance(catDeq.begin(), resultPair.first) << " (从0开始)" << endl;
cout << "年龄最大的猫咪的年龄是:" << (*resultPair.second).getAge() << endl;
cout << "一共出现了 " << count(catDeq.begin(), catDeq.end(), (*resultPair.second).getAge()) << " 次" << endl;
cout << "其中一只出现的位置是:" << distance(catDeq.begin(), resultPair.second) << " (从0开始)" << endl;// 最后一只
cout << "所有猫咪的年龄: [ ";
for (deque<Cat>::iterator iter = catDeq.begin(); iter != catDeq.end(); ++iter)cout << (*iter).getAge() << " ";
cout << "]" << endl;
return EXIT_SUCCESS;
}