Multimap的遍历和删除(很重要)
生活随笔
收集整理的這篇文章主要介紹了
Multimap的遍历和删除(很重要)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
c++STL容器中Multimap可允許重復鍵值元素插入容器,但在遍歷的時候出現了一些問題。今天要把他解決掉
?
第一元素是鍵值,不能修改。第二元素是實值,可以修改。
鍵值key與元素value的映照關系是多對多的關系,沒有定義[ ]操作運算
map中的所有元素都是pair
?
#include<cstdio> #include<iostream> #include<string> #include<map>using namespace std;struct student{char name[10];int age;char city[10];char phone[10]; };int main() {student s[] = {{"魏晶", 21, "蘭州", "xxx"},{"郭亨寧", 21, "太原", "xxx"},{"馬瑞敏", 21, "忻州", "xxx"},{"女", 45, "太原", "xxx"}};pair<int, student>p1(4, s[0]);pair<int, student>p2(2, s[1]);pair<int, student>p3(3, s[2]);pair<int, student>p4(4, s[3]);multimap<int, student>mm;mm.insert(p1);mm.insert(p2);mm.insert(p3);mm.insert(p4);//遍歷********我就是這塊不會/*typedef multimap<int, student>::iterator it;pair<it, it>p;for(it i = p.first; i != p.second; i++){cout << i -> second.name << endl;}*/for(multimap<int, student>::iterator it = mm.begin(); it != mm.end(); it++){cout << (*it).first << " " << it->second.name << " " << it->second.age << " " << it->second.city << " " << it->second.phone << endl;} }?
?
自己應用了一下:
#include<cstdio> #include<iostream> #include<map> #include<algorithm>using namespace std;const int maxn = 1e5;int main() {int n;scanf("%d", &n);multimap<int, string>mm;for(int i = 0; i < n; i++){string s; cin >> s;int k; cin >> k;mm.insert(make_pair(k, s));}multimap<int, string>::iterator it;cout << endl;for(it = mm.begin(); it != mm.end(); it++){cout << (*it).first << " " << (*it).second << endl;} }/*測試數據: 10 jfdl 1 dffd 2 fsd 3 ddf 10 dfdf 0 dffd 2 dgfd 6 dgf 3 sdfgd 8 dfds 90 dfdf 1 jfdl 2 dffd 2 dffd 3 fsd 3 dgf 6 dgfd 8 sdfgd 9 dfds 10 ddf*/?
一道可以用到multimap存儲,遍歷,刪除操作的題目。終于了解啦
C. Alphabetic Removals (cf)
附代碼:
#include<cstdio> #include<iostream> #include<cstring> #include<string> #include<vector> #include<algorithm> #include<set> #include<map>using namespace std;const int maxn = 4*1e5+5; char arr[maxn]; char result[maxn];int main() {int n, k;scanf("%d%d", &n, &k);string s; cin >> s;if(n <= k) return 0;multimap<char, int>mm;for(int i = 0; i < n; i++){mm.insert(make_pair(s[i], i));}multimap<char, int>::iterator it, it1;for(it = mm.begin(); it != mm.end(); ){mm.erase(it++); //multimap的刪除操作,注意 k--;if(k == 0) break; }for(it = mm.begin(); it != mm.end(); it++){arr[(*it).second] = (*it).first;}int cnt = 0;for(int i = 0; i < n; i++){if(arr[i] >= 'a'&&arr[i] <= 'z'){result[cnt++] = arr[i];}}for(int i = 0; i < cnt; i++) cout << result[i]; printf("\n");return 0; }?
總結
以上是生活随笔為你收集整理的Multimap的遍历和删除(很重要)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阶乘的性质
- 下一篇: G - Bad Hair Day (单调