multimap的简单使用 一道数据输入,查询的问题

来源:互联网 发布:ysl 口红 知乎 编辑:程序博客网 时间:2024/05/18 22:53


cmd是用来接受命令的

然后需要把st中的元素插入mp中,虽然它们是可以对应起来的,但是毕竟类型是不同的

所以不能直接把st给插进去

那我们能够插入的是什么呢。

我们需要make a pair 就是make_pair这样的函数

            mp.insert(make_pair(st.score,st.info));

生成这个函数的时候,我们需要给他赋两个值

如果要查询的话,就用lower_bound来查找

你牛,我看不懂了,再会。

#include <cstdio>#include <iostream>#include <map>using namespace std;struct StudentInfo{    char name[20];    int id;};struct Student{    int score;    StudentInfo Info;};typedef multimap<int,struct StudentInfo> Multi_map;int main(){    Multi_map st;    while (1){        char temp[20];        cin >> temp ;        if (temp[0] == 'E')break;        if (temp[0] == 'A'){            Student a;            cin >> a.Info.name >> a.Info.id >> a.score;            st.insert(make_pair(a.score,a.Info));        }        else if (temp[0] == 'Q'){            Multi_map::iterator p;            int idMax;            //  他怎么知道我是first呢。            int scoreOne;            cin >> scoreOne ;            p = st.lower_bound(scoreOne);            if(p != st.begin()){                p --;                Multi_map::iterator maxp = p;                idMax = p->second.id;                for (;p!=st.begin() && p->first != maxp->first; p--){                    if (idMax < p->second.id){                        idMax = p->second.id;                        maxp = p;                    }                }                //不能漏掉了begin了                if (p == st.begin()){                    if (idMax < p->second.id){                        idMax = p->second.id;                        maxp = p;                    }                }                cout << maxp->second.name << " ";                cout << maxp->second.id << " ";                cout << maxp->first <<endl;            }            else cout << "Nothing to find!" << endl;        }    }    Multi_map::iterator i;    for (i = st.begin();i != st.end();i ++){        cout << i->second.name << " ";        cout << i->second.id << " ";        cout << i->first <<endl;    }    return 0;}

这个是我自己弄得哦

其中有一些感悟很深。首先,要访问map中的函数,必须要借助first和second来帮助

其次,由于迭代器的限制,我们只能靠着在访问一次来保证数据的完整性。

                for (;p!=st.begin() && p->first != maxp->first; p--){                    if (idMax < p->second.id){                        idMax = p->second.id;                        maxp = p;                    }                }                //不能漏掉了begin了                if (p == st.begin()){                    if (idMax < p->second.id){                        idMax = p->second.id;                        maxp = p;                    }                }

这个就是例子,我们必须要进行判断两次

还有struct 的完美使用,可以迎合multimap的使用。

原创粉丝点击