思路分析:
这道题本身是很有意义的,只是被简化了反倒显得很无趣。
请让我们站在实际的情况下思考这个问题:
1. 设如果最年长和最年轻的人有并列,则按字母序输出名字;
2. 保证镇上每个人的名字是唯一的,即名字作为个人ID,不存在重名现象;
其他条件不变,请尝试编程实现。
先贴出原题示例代码:
#include<iostream>
#include<set>
using namespace std;
class Person {
public:
Person() {
}
Person(const string& name,const string& birthday) {
this->name = name;
this->birthday = birthday;
}
public:
string name;
string birthday;
};
//仿函数,指导set排序
struct SortPerson
{
bool operator()(const Person& p1, const Person& p2) {//日期升序排列
if (p1.birthday < p2.birthday) {
return true;
}
else if (p1.birthday == p2.birthday) {
return p1.name < p2.name;
}
return false;
}
};
int main() {
//由于日期格式是一致的,使用string就可以判断大小
int num;
cin >> num;
int all = 0;
set<Person, SortPerson> se;
for (int i = 0; i < num; i++) {//存元素
string name;
string birthday;
cin >> name >> birthday;
if (birthday >= "1814/09/06" && birthday <= "2014/09/06") {//日期合理
Person p(name, birthday);
all++;
se.insert(p);
}
}
if (se.size() == 0) {
cout << 0;
return 0;
}
Person youngest = *se.rbegin();//指向最后一个元素的反向迭代器
Person oldest = *se.begin();
cout << all << " " << oldest.name << " " << youngest.name;
return 0;
}
下面是变形题的代码:
#include<iostream>
#include<set>
#include<vector>
using namespace std;
/*
**************这里是变形题的代码,请不要搞错了!!******************
*/
class Person {
public:
Person() {
}
Person(const string& name,const string& birthday) {
this->name = name;
this->birthday = birthday;
}
public:
string name;
string birthday;
};
//仿函数,指导set排序
struct SortPerson
{
bool operator()(const Person& p1, const Person& p2) {//日期升序排列
if (p1.birthday < p2.birthday) {
return true;
}
else if (p1.birthday == p2.birthday) {
return p1.name < p2.name;
}
return false;
}
};
int main() {
//由于日期格式是一致的,使用string就可以判断大小
int num;
cin >> num;
set<Person, SortPerson> se;
for (int i = 0; i < num; i++) {//存元素
string name;
string birthday;
cin >> name >> birthday;
if (birthday >= "1814/09/06" && birthday <= "2014/09/06") {//日期合理
Person p(name, birthday);
se.insert(p);
}
}
if (se.size() == 0) {
cout << 0;
return 0;
}
Person youngest = *se.rbegin();//指向最后一个元素的反向迭代器
Person oldest = *se.begin();
vector<Person> youns,olds;//存放年龄最小和最大的人
//筛选年龄最大和最小的人们
for (set<Person, SortPerson>::iterator it = se.begin(); it != se.end(); it++) {
if ((*it).birthday <= oldest.birthday) {
olds.push_back(*it);
oldest = *it;
}
else if ((*it).birthday >= youngest.birthday) {
youns.push_back(*it);
youngest = *it;
}
}
//输出
cout << se.size() << " ";//输出日期合理总人数
if (youns.size() > 0) {
//输出年长的人
for (int i = 0; i < olds.size(); i++) {
cout << olds[i].name<<" ";
}
//输出年少的人
for (int i = 0; i < youns.size() - 1; i++) {
cout << youns[i].name << " ";
}
cout << youns[youns.size() - 1].name;
return 0;
}
else {
//最年长与最年少的为同一人
cout << olds[olds.size() - 1].name<<" ";
cout << olds[olds.size() - 1].name;
}
}