没有学过C++的STL,也没有用过map,基本上是把别人代码照抄一遍。
定义一个map:
map<string, int> tree
find()函数返回的是一个迭代器,如果没有要查找的结构,则指向end(),可以通过tree[name]来访问具体元素
if (tree.find(name) == tree.end()) { tree[name] = 1; } else { tree[name]++; }
定义一个迭代器(游标)it,用来遍历map
map<string, int>::iterator it;
for循环中it刚开始指向map的第一个元素,每次递增1位,当指向end()时结束循环
用(*it)访问map中的元素
for (it = tree.begin(); it != tree.end(); it++) { double perc = (*it).second*1.0 / N * 100; if (it == tree.end()) { cout << (*it).first << " " << fixed << setprecision(4) << perc << '%'; } else cout << (*it).first << " " << fixed << setprecision(4) << perc << '%' <<endl; }
#include <iostream> #include <string> #include <cstring> #include <map> #include<iomanip> using namespace std; int main() { int N; map<string, int> tree; cin >> N; getchar();//原文也提醒了,不加getchar()不能通过,因为第一个接收的字符串为空了 string name; for (int i = 0; i < N; i++) { getline(cin, name); if (tree.find(name) == tree.end()) { tree[name] = 1; } else { tree[name]++; } } map<string, int>::iterator it; for (it = tree.begin(); it != tree.end(); it++) { double perc = (*it).second*1.0 / N * 100; if (it == tree.end()) { cout << (*it).first << " " << fixed << setprecision(4) << perc << '%'; } else cout << (*it).first << " " << fixed << setprecision(4) << perc << '%' <<endl; } return 0; }