c++ - 如何编写一个算法来找出特定单词出现在哪些行中(我正在使用 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 文件行中。泰
解决方案
这看起来像是一个你想自己做的学习练习,我有一个不为那些编写代码的政策。
但是,您可以做的一件事是计算您遇到的换行符的数量(它会告诉您当前所在的行),并且每当您看到要搜索的文本时,将当前行号插入到 a std::set<unsigned>
orstd::vector<unsigned>
中。
您可能希望在一个循环中执行此操作,可能一次读取一行。无论您遇到搜索词,更新单词计数器和行号集。
推荐阅读
- swift - UITap手势不显示相册
- anylogic - 在 Anylogic 中为代理参数分配不同值的正确方法是什么?
- nearprotocol - python后端中近协议的JWT身份验证
- python - 为什么有时 Python 代码中有 obj_method = obj.method 模式?
- python-3.x - 为什么sqlite在python程序中会抛出语法错误?
- ruby-on-rails - 未初始化的常量 Bundler::thor
- javascript - 如何在实时数据库中增加整数值?
- ios - Swift,将数据从动态单元格行选择传递到弹出视图控制器
- r - ggplot2:为 geom_freqpoly 产生的平均计数值添加行
- c++ - 如何理解`std::make_shared