c++ - 需要 C++ 使用 map 来跟踪输入文件中的单词的帮助

标签 c++ stl maps

假设我有一个文本文件

today is today but
tomorrow is today tomorrow

然后使用 map 如何跟踪重复的单词?它在哪一行重复? 到目前为止,我已将文件中的每个字符串作为临时文件读入,并按以下方式存储:

    map<string,int> storage;

    int count = 1 // for the first line of the file

    if(infile.is_open()){
     while( !infile.eof() ){ 
      getline(in, line);
      istringstream my_string(line);
      while(my_string.good()){
         string temp;
         my_string >> temp;

    storage[temp] = count
    }
    count++;// so that every string read in the next line will be recorded as that line.
}
}
   map<string,int>::iterator m;
   for(int m = storage.begin(); m!= storage.end(); m++){
      out<<m->first<<": "<<"line "<<m->second<<endl;
}

现在输出只是

but: line 1
is: line 2
today: line 2
tomorrow: line 2

但是相反.. 它应该打印出来(没有重复的字符串):

today : line 1 occurred 2 times, line 2 occurred 1 time.
is: line 1 occurred 1 time, line 2 occurred 1 time.
but: line 1 occurred 1 time.
tomorrow: line 2 occurred 2 times.

注意:字符串的顺序无关紧要。

如有任何帮助,我们将不胜感激。谢谢。

最佳答案

map 存储具有唯一键的(键,值)对。这意味着如果您多次分配给同一个键,则只会存储您分配的最后一个值。

听起来您想要做的不是将线存储为值,而是要存储另一个线图 -> 出现次数。

所以你可以像这样制作你的 map :

typedef int LineNumber;
typedef int WordHits;
typedef map< LineNumber, WordHits> LineHitsMap;
typedef map< string, LineHitsMap > WordHitsMap;
WordHitsMap storage;

然后插入:

WordHitsMap::iterator wordIt = storage.find(temp);
if(wordIt != storage.end())
{
    LineHitsMap::iterator lineIt = (*wordIt).second.find(count);
    if(lineIt != (*wordIt).second.end())
    {
        (*lineIt).second++;
    }
    else
    {
        (*wordIt).second[count] = 1;
    }
}
else
{
    LineHitsMap lineHitsMap;
    lineHitsMap[count] = 1;
    storage[temp] = lineHitsMap;
}

关于c++ - 需要 C++ 使用 map 来跟踪输入文件中的单词的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3063987/

相关文章:

IOS:在 iPad 中将 curl 效果作为 map

c++ - C++ 中的 HTTP 获取请求

c++ - 如何在 Windows 上使用 QtCreator 为 Linux 构建和调试应用程序?

javascript - 将对象数组减少为键值对映射,保留值数组中的重复条目

c++ - 如何将多个 std::function 合并为一个?

c++ - 使用 std::vector 作为可变的、完全填充的数组?

api - 在 Google Maps API 上显示 Shapefiles .shp 区域和标记?

c++ - 在 perl 中调试由 SWIG 包装的共享库

c++ - 模板化双模板类方法

c++ - 使用先前 move 过的输出迭代器调用 move() 是标准 C++ 吗?