c++ - 如何解决索引和排序的问题

标签 c++ indexing text

我有个问题。有一个文本文件,你需要找到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/

相关文章:

c++ - 在没有条件/分支的情况下使用逻辑 AND/OR

javascript - 在 focusout/blur 上检索文本

java - 如何拆分文本文件并在一行中存储 2 个值?

javascript - 如何将输入字段放在左侧,将文本标签放在右侧?

c++ - XCode 升级到 4.4.1,现在我在 STL <vector> 中编译时遇到错误

c++ - 从没有正则表达式的字符串解析int?

Delphi TChart - 如何从 x,y 鼠标坐标获取系列索引而不单击它

hadoop - 如何使用外部表和 serde 优化 Hive queires

c++ - 对以下 c/c++ 解决方案的逻辑解释

mysql - Like 查询如何与索引表一起使用