#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<iterator>
#include<algorithm>
using namespace std;
void Query(const string &word, int &numLine, map<int,string>&MapIntoStr,const vector<string>&LineString,const map<string,set<int>> &MapStoSet)
{
auto ret = MapStoSet.find(word);
if (ret != MapStoSet.end())
{
auto setin = ret->second;
numLine = setin.size();
auto wz = setin.begin();
string str;
while (wz != setin.end())
{
str = LineString[*wz-1];
MapIntoStr.insert(make_pair(*wz, str));
++wz;
}
}
else
numLine = 0;oid print(const string &word, int numLine,const map<int,string>&MapIntoStr)
{
cout <<word<< " occurs " << numLine << ((numLine> 1) ? " times" : " time") << endl;
for (auto map_it = MapIntoStr.cbegin(); map_it != MapIntoStr.cend(); ++map_it)
{
cout << "(line " << map_it->first << ") " << map_it->second << endl;
}
}
void getText(vector<string>&LineString, map<string, set<int>>&MapStoSet, ifstream& infile)
{
string str;
int i = 1;
while(getline(infile,str))
{
LineString.push_back(str);
istringstream istr(str);
string word;
set<int>setin = {i};
while (istr >> word)
{
auto ret = MapStoSet.insert(make_pair(word, setin));
if (!ret.second)
(ret.first)->second.insert(i);
}
++i;
}
}
int main()
{
ifstream infile("wordtext.txt");
vector<string>LineString;
map<string, set<int>> MapStoSet;
string word;
int numLine;
map<int, string> MapIntoStr;
cout << "Please Enter word to look for" << endl;
cin >> word;
getText(LineString,MapStoSet,infile);
Query(word,numLine,MapIntoStr,LineString,MapStoSet);
print(word, numLine, MapIntoStr);
return 0;
}