学习视频09-常用 STL视频讲解(C++ 版)_哔哩哔哩_bilibili
S:map
map<string, int> dict;
dict.insert(make_pair("Tom", 1));
dict.insert(make_pair("Jone", 2));
dict.insert(make_pair("Mary", 1));
dict.insert(make_pair("Tom", 2)); //不会更改值
//{"Tom"->1, "Jone"->2,"Mary"->1}
dict["Tom"] = 3;//可以
//遍历:用迭代器
for (map<string, int>::iterator it = dict.begin(); it != dict.end(); it++) {
cout << it->first << it->second << '\n';
}
map
map例子
map<string, int> dict;
dict["Tom"] = 1;
dict["Jone"] = 2;
if (dict.count("Tom")) {
cout << "Tom is in class " << dict["Tom"] << endl;
}
for (map<string, int>::iterator it= dict.begin(); it != dict.end(); it++) {
cout << it->first << " is in class " << it->second << '\n';
}
S:二维map
map<int, map<string, int>> info;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int id;
string s;
cin >> id >> s;
info[id][s]++;
}
map<int, map<string, int>>::iterator it1;
map<string, int>::iterator it2;
for (it1 = info.begin(); it1 != info.end(); it1++) {
for (it2 = it1->second.begin(); it2 != it1->second.end(); it2++) {
cout << endl;
cout << "There are " << it2->second << " people named " << it2->first << " in class " << it1->first;
}
}
Q:打印锯齿矩阵
int n, m;
cin >> n >> m;
int x, y;
vector<vector<int>> vec(n, vector<int>(0));
for (int i = 0; i < m; i++) {
cin >> x >> y;
vec[x-1].push_back(y); //!!索引越界
}
for (int i = 0; i < n; i++) {
if (vec[i].empty())
cout << '\n';
else {
for (int j = 0; j < vec[i].size(); j++) {
cout << vec[i][j] << " ";
}
cout << '\n';
}
}
return 0;
Q:破案
struct people {
int h;
int w;
int age;
people(int _h, int _w, int _age) {
h = _h;
w = _w;
age = _age;
} //构造函数
bool operator<(const people& rhs)const {
if (h != rhs.h) {
return h < rhs.h;
}
if (w != rhs.w) {
return w < rhs.w;
}
return age < rhs.age;
}
};
set<people> s;
int main()
{
int n, m, h, w, age;
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> h >> w >> age;
s.insert(people(h, w, age));
}
for (int i = 0; i < m; i++) {
cin >> h >> w >> age;
if (s.count(people(h, w, age)))
cout << "Yes" << '\n';
else
cout << "No" << endl;
}
return 0;
}
要写全bool operator<(const people &rhs)const{}
Q:藏书
int main()
{
int n;
cin >> n;
string name;
map<string, int> books;
for (int i = 0; i < n; i++) {
cin >> name;
books[name]++;
}
cout << books.size() << endl;
for (map<string, int>::iterator it = books.begin(); it != books.end(); it++) {
cout << it->first << " " << it->second << '\n';
}
return 0;
}