PTA 1039 Course List for Student
2019-03-17 本文已影响0人
smatrcHendsa
Map, vector, iterator
https://pintia.cn/problem-sets/994805342720868352/problems/994805447855292416
use map<string, vector<int> >:: iterator it = mp.find(sname[i]); to return the element's iterator.
出现了vector的元素为0打印不出来 我就往里面塞了个-1 强行让它不等于零
不是vector的锅 是map里面我没加这个元素 元素还没创建
所以会runtime error
加个这个mp[sname[i]];
让它创建
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
int main() {
int N, K;
scanf("%d %d", &N, &K);
map<string, vector<int> > mp;
//input courses
for (int i = 0; i < K; i++) {
int th, cnt;
scanf("%d %d", &th, &cnt);
for (int j = 0; j < cnt; j++) {
string st;
cin >> st;
mp[st].push_back(th);
}
}
vector<string> sname;
//input student name
for (int i = 0; i < N; i++) {
string st;
cin >> st;
sname.push_back(st);
}
for (int i = 0; i < sname.size(); i++) {
cout << sname[i];
mp[sname[i]]; //让它非空
map<string, vector<int> >:: iterator it = mp.find(sname[i]);
vector<int> vec = it->second;
printf(" %d", vec.size());
sort(vec.begin(), vec.end());
for (int j = 0; j < vec.size(); j++) {
printf(" %d", vec[j]);
}
printf("\n");
}
return 0;
}