C++ STL MultiMap 简单应用

一个简单的成绩录入和查询系统

接受两种输入:

add  name no score

query score

name 代表姓名  score代表分数 no代表学号  name和score可重复  no不可重复

两种输入可以交替出现  

add 表示添加  

query 表示查询  碰到查询 输出已有记录中分数比score低的最大分的学生信息,如果有多个满足的就输出学号最大的,找不到则输出 nobody

 1 #include<iostream>
 2 #include <string>
 3 #include<map>
 4 #include<utility>//for make_pair
 5 using namespace std;
 6 struct Info{
 7     int no;
 8     string name;
 9 };
10 using Map = multimap<float, Info>;
11 int main()
12 {
13     Map m;
14     string word;
15     Info info;
16     int score;
17     cout << " enter add to insert q to quit other is query\n";
18     while (cin>>word&&word!="q")
19     {
20         if (word == "add")
21         {
22             cin >> info.name >> info.no >> score;
23             m.insert(make_pair(score, info));
24         }
25         else if(word=="query"){
26             int s;
27             cout << "enter the score which you want\n";
28             cin >> s;
29             auto iter = m.lower_bound(s);
30             //iter lower_bound(const T&val)
31             //找到一个最大的位置iter[begin,iter)中所有元素都比val小 此时iter的位置不可用
32             if (iter != m.begin())
33             {
34                 --iter;
35                 s = iter->first;//比要查询分数低的最高分
36                 auto maxiter = iter;
37                 int maxno = iter->second.no;
38                 for (; iter != m.begin() && iter->first == s; --iter)//倒着往前查找
39                 {
40                     if (iter->second.no > maxno)
41                     {
42                         maxno = iter->second.no;
43                         maxiter = iter;
44                     }
45                 }
46                 if (iter->first == score)//p到达begin退出的循环
47                 {
48                     if (iter->second.no > maxno)//判断begin位置的成员的no是否大于当前的
49                     {
50                         maxno = iter->second.no;
51                         maxiter = iter;
52                     }
53                 }
54                 cout << maxiter->second.name << " " << maxiter->second.no
55                     << " " << maxiter->first<<endl;
56             }//end iter != m.begin()
57             else
58                 cout << " nobody \n";
59             
60 
61         }//end else if
62 
63     }//end while
64     system("pause");
65     return 0;
66 }

猜你喜欢

转载自www.cnblogs.com/zydark/p/9470777.html