假设我有一个文本文件
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/