C++primer CH12智能指针
生活随笔
收集整理的這篇文章主要介紹了
C++primer CH12智能指针
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
智能指針就是可以自己計算指針所指向的對象是否需要釋放,也就是不用自己寫deete p.
#pragma once #ifndef QUERYRESULT #define QUERYRESYLT#include <string> using std::string;#include <vector> using std::vector;#include <memory> using std::shared_ptr;#include <sstream> #include <algorithm> #include <iostream> #include <fstream> #include <map> #include <set>class QueryResult;class TextQuery { public:using lineNo = vector<string>::size_type;TextQuery(std::ifstream&);QueryResult query(const string&) const; private:shared_ptr<vector<string>> input;std::map<string, shared_ptr<std::set<lineNo>>> result; }; TextQuery::TextQuery(std::ifstream& ifs) :input(new vector<string>) {lineNo lineNoV{ 0 };for (string line; std::getline(ifs, line); ++lineNoV) {//++lineNov是一個size_t 類型的局部變量input->push_back(line);std::istringstream line_stream(line);for (string text, word; line_stream >> text; word.clear()) { avoid read a word followed by punctuation(such as: word, )std::remove_copy_if(text.begin(), text.end(), std::back_inserter(word), ispunct);auto& nos = result[word];if (!nos) nos.reset(new std::set<lineNo>);nos->insert(lineNoV);}} }class QueryResult { public:friend std::ostream& print(std::ostream&, const QueryResult&);QueryResult(const string& s, shared_ptr<std::set<TextQuery::lineNo>> set,shared_ptr<vector<string>> v) :word(s), nos(set), input(v) {}; private:string word;shared_ptr<std::set<TextQuery::lineNo>> nos;shared_ptr<vector<string>> input; };QueryResult TextQuery::query(const string& str) const {//use static just allocate oncestatic shared_ptr<std::set<lineNo>> nodata(new std::set<lineNo>);auto found = result.find(str);if (found == result.end()) return QueryResult(str, nodata, input);elsereturn QueryResult(str, found->second, input);}std::ostream& print(std::ostream& out, const QueryResult& qr) {out << qr.word << " occurs " << qr.nos->size() << (qr.nos->size() > 1 ? " times" : " time") << std::endl;for (auto i : *qr.nos)out << "\t(line " << i + 1 << ") " << qr.input->at(i) << std::endl;return out; }#endif #include "QueryResult.h" #include <iostream>void runQueries(std::ifstream& infile) {TextQuery tq(infile);while (true) {std::cout << "enter word to look for, or q to quit: ";string s;if (!(std::cin >> s) || s == "q") break;print(std::cout, tq.query(s)) << std::endl;} }int main() {std::ifstream file("test.txt");runQueries(file); }總結
以上是生活随笔為你收集整理的C++primer CH12智能指针的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 图像工程之图像处理 CH1绪论
- 下一篇: 图像处理傅里叶变换的理解及其matlab