c++ - 我可以使用 C++ 中的唯一命令来获取频率吗

标签 c++ vector

我想获取存储在 vector 中的单词的频率。我已经多次用谷歌搜索我的问题,但没有找到对我有用的东西。我找到了一个网站,其中有人说要使用 unique 命令来计算单词的频率,但我找不到有关如何完成此操作的任何示例。

最佳答案

使用 <a href="http://cplusplus.com/reference/stl/map/" rel="noreferrer noopener nofollow">map</a><string, unsigned> 创建一个 histogram :

using std::string;
using std::map;
using std::vector;

typedef map<string, unsigned> counts_t;

// Create the histogram
counts_t histogram;
for (vector<string>::const_iterator i = vec.begin(); i != vec.end(); ++i)
    ++histogram[*i];

// ... and display it.
for (counts_t::const_iterator i = histogram.begin(); i != histogram.end(); ++i) {
    double freq = static_cast<double>(i->second) / vec.size();
    std::cout << i->first << ": " << freq << "\n";
}

关于c++ - 我可以使用 C++ 中的唯一命令来获取频率吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9616913/

相关文章:

c++ - 功能范围不正确的输出

C++11/14/17,GCC 7 与 GCC 8 : Name lookup for friend class templates

c++ - 哪个 vector 地址更安全?

c++ - 调整二维变量C++的大小

c++ - 使用 C++ 从定界符拆分字符串中提取整数数组

c++ - Vector::at 与 vector::operator[]——不同的行为

c++ - C++读取访问冲突,结构 vector

c++ - std::vector::resize() 与 std::vector::reserve()

c++ - 释放存储在 vector 中的对象?

arrays - 如何使用函数初始化数组?