向量中的常用单词用C++表示单词出现的次数
Common word in vector with how many times word occurred C++
大家好,我正在努力找出如何在向量中找到常用词,以及它发生了多少次。我的教授希望我们用两个for循环来遍历向量,但我被卡住了,因为循环会重新计算已经计数的单词,并给出疯狂的输出。我是第一堂编程课的新程序员,发现这一切都很困难。这就是我到目前为止所拥有的。
#include <iostream>
#include <vector>
using namespace std;
int main() {
string s;
int max_count {1};
vector<string> input{};
while (cin >> s)
{
input.push_back(s);
}
for (int i = 0; i < input.size(); ++i)
{
for (int k = i + 1; k < input.size(); ++k)
{
if (input[i] == input[k])
{
s = input[k];
++max_count;
}
}
}
cout << s << " occurs " << max_count << " times " << endl;
return 0;
}
不使用额外数据结构的简单解决方案:
int prevRel = -1;
std::string last = "";
for (int i = 0; i < input.size(); ++i)
{
int relcount = 0;
for (int k = 0; k < input.size(); ++k)
{
if (input[i] == input[k])
relcount++;
}
if(relcount > prevRel) {
prevRel = relcount;
last = input[i]
}
}
解决方案现在在last
中,prevRel
出现的绝对次数
这使用了一个映射,因此需要遍历单词列表,并使用二进制搜索来找到可能匹配的单词,这意味着输入的单词越多,效率就越高。如果你多输入十倍的单词,这个单词的运行速度会慢不到十倍。
在此处运行
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main() {
vector<string> input
{ "the", "quick", "brown", "fox", "jumped",
"over", "the", "the", "lazy", "dog" };
map< string, int > histogram;
string most_common_word = input[0];
int max_count = 1;
// loop over words
for( auto& word : input)
{
// attempt to insert new word into histogram
auto p = histogram.insert( pair< string, int >( word, 1 ) );
if( ! p.second )
{
// word is not new, so increment count
p.first->second++;
// check for most common so far
if( p.first->second > max_count )
{
// remember most common so far
most_common_word = word;
max_count = p.first->second;
}
}
}
cout << "'" << most_common_word << "' occurs " << max_count << " times " << endl;
return 0;
}
相关文章:
- 当字符串是某个单词时给出输出?
- 打印出使用地图实现的Trie中的所有单词
- 如何在带有给定特定前缀的向量中打印出单词
- 如何用'auto'单词推导出哪种类型的参数编写函数?
- 找出两个给定单词和字典之间最短的单词阶梯
- 如何计算出现在字符串和输出行中的唯一单词?C
- 用输入中给出的单词填充字符串
- 给出错误的输出:如何将字符串分解为字典单词
- 使用线程根据起始字符打印出单词
- 当传递表示负值的十六进制时,C++stoll抛出超出范围的异常
- 向量中的常用单词用C++表示单词出现的次数
- OpenCV 聚类袋的单词 k 表示
- 打印出所有可能的固定长度单词
- C++程序(按字母顺序打印出n个单词)运行时错误
- 对列表中最有可能由列表顶部的人说出的积极单词和列表末尾很少说出的单词进行排序
- K-表示算法C++,交换出点
- 通过递归以相反的顺序打印出一行中的单词
- 在最近的K个单词中找出最频繁的单词
- 如何找出字符串中的特定单词
- 额外的单词出现在visualc++输出窗口