我想获取存储在 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/