iT邦幫忙

0

C++ Primer 5th Edition Exercises(練習題)12.28作答

Exercise 12.28: Write a program to implement text queries without defining
classes to manage the data. Your program should take a file and interact
with a user to query for words in that file. Use vector, map, and set
containers to hold the data for the file and to generate the results for the
queries.

寫一個沒有定義類別來處理資料的文字查詢程式。這個程式應該要帶有一個檔案的參數,並能與使用者互動來對該檔案的文字進行查詢。利用vector、map和set這些容器來存放該檔案的內容且產出查詢的結果。

https://play.google.com/books/reader?id=J1HMLyxqJfgC&pg=GBS.PT903
https://drive.google.com/file/d/140Kwtzv7xCWploxvSN41MHlHmXd4VUO-/view
臉書直播:
https://www.facebook.com/100003034306665/videos/2601219816655803
Youtube實境秀(101集,俟傳):

相關文章

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
#include<map>
#include<set>

using namespace std;
vector<string>vs;
map<string, set<size_t>>mpWord_lineNum;
map<string, set<size_t>>::iterator mpIter;

void qureyData(ifstream& ifs) {//配置好檢索資料
	string wordLine;
	size_t lineNum(0);
	while (!ifs.eof() && getline(ifs, wordLine))
	{
		vs.push_back(wordLine);
		lineNum++;
		istringstream is(wordLine);
		string word;
		while (is >> word)
		{
			mpIter = mpWord_lineNum.find(word);
			if (mpIter == mpWord_lineNum.end()) {
				set<size_t>st_lineNum;
				st_lineNum.insert(lineNum);
				mpWord_lineNum.insert(make_pair(word, st_lineNum));
			}
			else//若map中已有此字
				mpIter->second.insert(lineNum);
		}
	}
}
void query(string& searchWord) {
	mpIter = mpWord_lineNum.find(searchWord);
	if (mpIter == mpWord_lineNum.end())
	{
		cout << "沒有找到\"" << searchWord << "\"字!" << endl;
	}
	else
	{
		size_t s = mpIter->second.size();
		cout << endl;
		cout << searchWord << " occurs " << s << ((s > 1) ? " times" : " time") << endl;
		for (size_t s : mpIter->second)
			cout << "\t(line " << s << ") " << vs[s-1] <<endl;		
		cout << endl;
	}
}

int main() {
	string strSearch;
	cout << "請指定要檢索的檔案全名(fullname,含路徑與副檔名)" << endl;
	if (cin >> strSearch);
	//必須檢查檔案存不存在	
	else//若沒有指定檔案的話
	{
		strSearch = R"(V:\Programming\C++\input.txt)";//"V:\\Programming\\C++\\input.txt";
	}
	ifstream ifs(strSearch);
	qureyData(ifs);
	cin.clear();
	while (true)
	{
		cout << "請輸入檢索字串,或輸入「q」離開" << endl;
		if (!(cin >> strSearch) || strSearch == "q") break;
		query(strSearch);
	}
}

https://github.com/oscarsun72/prog1-C-Primer-5th-Edition-s-Exercises/blob/exercise12_28/prog1/prog1.cpp


尚未有邦友留言

立即登入留言