输出重复出现字符串中最多的一个
需要C++11的支持。
源代码:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <utility>
using namespace std;
void Count() {
string temp_str, str;
auto count_num = 0, temp_count1 = 0, temp_count2 = 0;
vector<pair<size_t, string>> temp_vec_pair1, temp_vec_pair2;
vector<string> temp_vec, temp_vec1;
cout << "请输入字符串:" << endl;
cin >> temp_str;
//存入vector,方便操作。
for (auto &i : temp_str) {
str = i;
temp_vec.push_back(str);
}
//确定字符出现次数
for (auto &i : temp_vec) {
temp_count1 = count(temp_vec.begin(), temp_vec.end(), i);
auto temp_it = find(temp_vec1.begin(), temp_vec1.end(), i);
if (temp_it == temp_vec1.end()) {
temp_vec1.push_back(i);
temp_vec_pair1.push_back(make_pair(temp_count1, i));
}
}
//排序出现次数
stable_sort(temp_vec_pair1.begin(), temp_vec_pair1.end(), [](pair<size_t, string> p1, pair<size_t, string> p2)-> bool {
return p1.first > p2.first; });
//提取出现次数最多且相同的字符
temp_vec_pair2.push_back(*temp_vec_pair1.begin());
for (auto &b : temp_vec_pair1) {
temp_count2 = temp_vec_pair1.begin()->first;
str = temp_vec_pair1.begin()->second;
if (temp_count2 == b.first && str != b.second) {
temp_vec_pair2.push_back(b);
}
}
//输出出现次数最多且相同的字符
for (auto &i : temp_vec_pair2) {
cout << i.second << " 出现次数最多为: " << i.first << " 次" << endl;
}
}
int main() {
Count();
return 0;
}