STL标准模板库编程--(二)

(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;
    }

运行结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值