我有个问题。有一个文本文件,你需要找到5个经常出现的单词。程序接收文件名。输出:按字母顺序排列的前 5 个单词。问题是索引没有更新,乱排序。请帮帮我。提前致谢。 这是代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int MAX = 100000;
string words[MAX];
int instances[MAX];
int cast = 0 ;
void insert (string input)
{
for (int i = 0 ; i < cast; i++ )
{
if (input == words[i] )
{
instances[i]++;
return ;
}
}
if (cast < MAX)
{
words [cast] = input ;
instances[cast] = 1;
cast ++;
}
else
{
return ;
}
return ;
}
int FindTop (string & word)
{
int TopCast = instances[0];
int TopIndex = 0;
for (int i = 1; i<cast; i++ )
{
if(instances[i] > TopCast )
{
TopCast = instances[i];
TopIndex = i;
}
}
instances[TopIndex] = 0;
word = words[TopIndex ];
return TopCast;
}
int main ()
{
string word;
string file;
cin>>file;
ifstream data (file);
while(data >> word)
{
insert(word);
}
for (int i = 0; i < 5 ; i++)
{
cout<<FindTop(word)<<" "<<word<<endl;
}
}
最佳答案
如下更新您的 FindTop() 函数
int FindTop (string & word)
{
int TopCast = instances[0];
int TopIndex = 0;
for (int i = 1; i<cast; i++ )
{
if(instances[i] > TopCast )
{
TopCast = instances[i];
TopIndex = i;
}
else if(TopCast == instances[i])
{
//for making sure you get the smallest word (asc order) first if multiple words
// have same frequency
if( words[TopIndex].compare(words[i]) > 0 )
{
TopCast = instances[i];
TopIndex = i;
}
}
}
instances[TopIndex] = 0;
word = words[TopIndex ];
return TopCast;
}
关于c++ - 如何解决索引和排序的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58690343/