输出重复出现字符串中最多的一个 C++实现

本文介绍了一个使用C++11实现的功能,该功能能够找出输入字符串中出现次数最多的字符,并统计这些字符的出现频率。通过使用STL容器如`vector`和`pair`,以及标准库函数如`count`和`stable_sort`,该程序能够高效地完成任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输出重复出现字符串中最多的一个

需要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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值