首页 > 解决方案 > 如何编写一个算法来找出特定单词出现在哪些行中(我正在使用 std::map)

问题描述

我正在编写代码来计算每个单词在文本中出现的次数(我做了这个任务),但我找不到计算这些单词出现在哪一行的方法。

我不知道从哪里开始。


#include "header.h"
int main()
{
     //read the input, keeping track of each word and how often we see it
     std::ifstream in("tekstas.txt"); // input file

    std::string input;
    std::map<std::string, int> counters; // store each word and an associated counter
    std::vector<char>CharVect; // vector that stores symbols i want to replace
    formuojuChar(CharVect); // pushbacking that vector with symbols
     for (unsigned int i = 0; !in.eof(); i++)
    {
        std::getline(in, input);
        std::transform(input.begin(), input.end(), input.begin(), ::tolower); // lowering letters so for example "Mom"= "mom"
        Replace(input,CharVect, ' '); // replace symbols with space
        std::stringstream read(input);
        std::string word;
        while (read >> word)
        {
            ++counters[word];
        }
     }
     std::ofstream out("isvestis.txt");
    std::cout<<"Words that appear more than once in the text: "<<std::endl;
    std::cout<<std::endl;
     for (std::map<std::string, int>::const_iterator it = counters.begin();it != counters.end(); ++it)
        {
            if((it->second)>1)
            {

                std::cout<<"'" <<it->first<<"' " <<"appears "<<it->second <<" times in lines: " ;
                /*
                 ANY IDEAS ?
                 */
                std::cout<<std::endl;

            }
        }
        return 0;

}


我希望输出显示该单词出现在哪个 .txt 文件行中。泰

标签: c++c++11

解决方案


这看起来像是一个你想自己做的学习练习,我有一个不为那些编写代码的政策。

但是,您可以做的一件事是计算您遇到的换行符的数量(它会告诉您当前所在的行),并且每当您看到要搜索的文本时,将当前行号插入到 a std::set<unsigned>orstd::vector<unsigned>中。

您可能希望在一个循环中执行此操作,可能一次读取一行。无论您遇到搜索词,更新单词计数器和行号集。


推荐阅读