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 9

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

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐