c++ 字典排序并统计字符串个数
作者:野牛程序员:2023-12-22 08:47:51 C++阅读 3040
给定一组字符串,可以使用C++中的std::map来实现字典排序并统计字符串个数。以下是一个简单的示例代码:
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::string> strings = {"apple", "orange", "banana", "apple", "banana", "grape"};
// 使用 std::map 来统计字符串个数
std::map<std::string, int> stringCount;
for (const auto& str : strings) {
stringCount[str]++;
}
// 将统计结果按照字典序排序
std::map<std::string, int> sortedStringCount(stringCount.begin(), stringCount.end());
// 打印排序后的结果
for (const auto& entry : sortedStringCount) {
std::cout << entry.first << ": " << entry.second << "个\\n";
}
return 0;
}这个程序首先使用std::map来统计每个字符串出现的次数,然后将std::map的内容复制到另一个std::map中,由于std::map会按照键的字典序排序,所以最终的结果是按照字典序排列的字符串及其出现次数。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:C++ 程序:按字典顺序对元素进行排序
- 下一篇:c++ 排列和字典序全排列解析
