(4)有学生信息5个(姓名,学号):
{张三,2011123}, {王二,2011235},{刘七,2012009},{唐六,2012676},{堂八,2010527}.
将姓名作为key,学号作为value,采用map容器进行装载,而后采用for_each统计2011,2012,2010级学生个数并输出,最后可分别输入姓名和学号后对容器进行信息查询(既可以用学号,也可以用姓名对容器进行查询)。
程序清单:
#include <map>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
//仿函数定义
class fun{
private:
int num;//年级人数
string str1;//年级
string str2;//学号
public ://构造函数
fun(string s):str1(s),num(0){
}
//计算年级人数
void operator()(pair<string,string> elem){
str2 = elem.second;
//寻找序号特点,只比较第2和第3位是否相等
if(str2[2] == str1[2] && str2[3] == str1[3])
num++;
}
//返回人数
operator int(){
return num;
}
};
int main(){
//定义容器
map<string,string> sinfo;
map<string,string>::iterator pos;
int count = 0;//年级人数计数器
string in; //查找字符串,姓名或学号
//向容器内填入值
sinfo.insert(make_pair("张三","2011123"));
sinfo.insert(make_pair("王二","2011235"));
sinfo.insert(make_pair("刘七","2012009"));
sinfo.insert(make_pair("唐六","2012676"));
sinfo.insert(make_pair("堂八","2010527"));
//计算2010年级的人数
count = for_each(sinfo.begin(),sinfo.end(),fun("2010"));
cout<<"2010 : "<<count<<endl;
//计算2011年级的人数
count = for_each(sinfo.begin(),sinfo.end(),fun("2011"));
cout<<"2011 : "<<count<<endl;
//计算2012年级的人数
count = for_each(sinfo.begin(),sinfo.end(),fun("2012"));
cout<<"2012 : "<<count<<endl;
//输入查找的姓名或学号
cout<<"input:"<<endl;
cin>>in;
//pos = sinfo.find(in);
cout<<"name"<<"\t"<<"number"<<endl;
//cout<<pos->first<<"\t"<<pos->second<<endl;
//没调用STL算法,遍历容器,只查找一个值后 ,输出,再退出
for(pos = sinfo.begin();pos != sinfo.end();++pos){
if(pos->first == in || pos->second ==in){
cout<<pos->first <<"\t"<<pos->second<<endl;
break;
}
}
//没有查找到,显示提示信息
if(pos == sinfo.end())cout<<"not exist"<<endl;
//完结
getchar();
getchar();
return 0;
}
运行结果: