map统计单词个数
用map统计字符串中每个字符出现的次数
#include <iostream> #include <vector> #include <string> #include <map> #include <algorithm> using namespace std; // map统计字符出现的次数 int main(int argc, char **argv) { string str = "slskdflsafd"; map<char, int>map1; for(int i = 0; i < str.size(); i++) { map1[str[i]]++; } for(auto it = map1.begin(); it != map1.end(); it++) { cout << it->first <<":"<<it->second << endl; } return 0; }
统计单词出现的个数
#include <iostream> #include <vector> #include <string> #include <map> #include <algorithm> int main(int argc, char **argv) { vector<string> vec(0); int N; cout << "输入单词个数:"; cin >> N; cout << "输入单词:" << endl; while(N--) { string str; cin >> str; vec.push_back(str); } map<string, int>map1; for(int i = 0; i < vec.size(); i++) { map1[vec[i]]++; } for(auto it = map1.begin(); it != map1.end(); it++) { cout << it->first <<":"<<it->second << endl; } return 0; }