1 #include 2 #include 3 #include 4 #include
>word_and_row; //使用map将每个单词与它出现的行号set关联起来,使用set可以保证行号不会重复且升序保存17 string s;18 while (getline(in, s))19 {20 row.push_back(s);21 }22 for (size_t i = 0; i < row.size(); ++i)23 {24 string word;25 istringstream read(row[i]); //使用istringstream来将每行分解为单词26 while (read >> word)27 word_and_row[word].insert(i);28 }29 30 string s1; //s1为待查找的单词。注意:待查找的单词不能与句号或逗号连在一起!31 while (cin >> s1 && s1 != "q" ) //输入q时终止输入32 if (word_and_row.find(s1) != word_and_row.end())33 {34 int i = word_and_row[s1].size();35 cout << s1 << " occurs " << i << " times" << endl;36 for (auto d : word_and_row[s1])37 cout << "(line " << d + 1 << ") " << row[d] << endl;38 39 }40 else41 {42 cout << "This word can not be found in this passage! Please input a word again: " << endl; 43 }44 in.close();45 46 return 0;47 }