C++Primer笔记——文本查询程序(原创,未使用类)

 

 

 

复制代码
 1 #include <iostream>
 2 #include <vector>
 3 #include <set>
 4 #include <map>
 5 #include <fstream>
 6 #include <sstream>
 7 #include <string>
 8 
 9 using namespace std;
10 
11 int main()
12 {
13     ifstream in;
14     in.open("C:\\Users\\HP\\Desktop\\passage.txt");
15     vector<string>row;                   //使用vector<string>来保存整个输入文件的一份拷贝,输入文件的每行保存为其中的每一个元素
16     map<string, set<int>>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         else
41         {
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 }
复制代码

 

posted @   拾月凄辰  阅读(301)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示
主题色彩