以下是使用C++20 ranges库实现字符串统计的示例代码:

#include <iostream>
#include <ranges>
#include <string>
#include <unordered_map>

int main() {
    std::string str = "hello world";
    std::unordered_map<char, int> freq_map;

    for (char c : str | std::views::filter(std::isalpha)) {
        ++freq_map[std::tolower(c)];
    }

    for (const auto& [ch, freq] : freq_map) {
        std::cout << ch << " : " << freq << '\n';
    }

    return 0;
}

这个例子使用了C++20中的ranges库来实现字符串统计。它通过管道操作符|将字符串转换为一个视图,并使用std::views::filter过滤出所有的字母字符。然后,它遍历每个字符并在一个std::unordered_map中记录每个字符的出现次数。最后,它遍历整个freq_map并输出每个字符及其出现次数。

c++20 ranges 实现字符串统计

原文地址: https://www.cveoy.top/t/topic/sFv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录