我正在尝试创建一个程序,该程序从 .txt 或类似文件中获取数据,并要求用户输入要搜索的单词。输出应在上下文中显示关键字,其中包含最初位于其前面和后面的 2 个单词。(例如:关键字:男孩会输出“男孩跑了”)我可以使用 equal_range() 函数在文件中找到关键字的所有实例,但是我不知道如何遍历地图中的数据访问上下文的其他词。到目前为止,这是我的代码:
typedef multimap<string, int> templateMap;
templateMap wordMap;
typedef pair<templateMap::iterator, templateMap::iterator> searchTemplate;
searchTemplate search;
typedef pair<templateMap::const_iterator, templateMap::const_iterator> innerIteratorTemplate;
multimap<string, int>::iterator tempMap;
string tempWord;
string keyword;
// omitted code
for (size_t i = 0; !inData.eof(); i++)
{
inData >> tempWord;
wordMap.insert(pair<string, int>(tempWord, i));
}
search = wordMap.equal_range(keyword);
for (multimap<string, int>::iterator itr = search.first; itr != search.second; ++itr)
{
cout << "The keyword " << keyword << " is found at location " << itr->second << endl;
tempMap = itr;
itr->second = itr->second - 2;
cout << itr->first << endl;
}
我知道底部 for 循环中的代码是错误的,但它是出于测试目的。