算法之字符串字符统计
分析和思路:用map建立字符映射,并赋值到pair结构里,然后用vector的sort 优先级排序
1 // PairTestTwo.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 2 // 3 4 #include <iostream> 5 #include <string> 6 #include "algorithm" 7 #include <map> 8 #include <vector> 9 using namespace std; 10 11 bool cmp0(pair<char, int> p1, pair<char, int> p2) 12 { 13 if (p1.second == p2.second) 14 return p1.first < p2.first; 15 else return p1.second > p2.second; 16 // else if (p1.second == p2.second) 17 // return p1.first <= p2.first; 18 19 } 20 21 int main() 22 { 23 string input; 24 while (cin >> input) 25 { 26 map<char, int>m; 27 pair<char, int>m_pair; 28 for (int i = 0; i < input.size(); i++) 29 { 30 m[input[i]] += 1; 31 } 32 map<char, int>::iterator iter = m.begin(); 33 vector<pair<char, int>> v; 34 35 36 //------这个地方是不是写的有点冗余?----- 37 for (iter = m.begin(); iter != m.end(); iter++) 38 { 39 m_pair.first = iter->first; 40 m_pair.second = iter->second; 41 v.push_back(m_pair); 42 } 43 //------这个地方是不是写的有点冗余?----- 44 // pair<char, int>m_pair; 45 46 sort(v.begin(), v.end(),cmp0); 47 for (int i = 0; i < v.size(); i++) 48 { 49 cout << v[i].first; 50 } 51 cout << endl; 52 int a = 5; 53 a = 6; 54 55 } 56 }
主要为了自己学习