Exercise 13.31: Give your class a < operator and define a vector of HasPtrs. Give that vector some elements and then sort the vector. Note when swap is called.
将您在之前练习做出来的那个HasPtr类别给它定义一个<运算子,且定义一个由HasPtr元素所组成的vector。加入一些元素到这个vector,然后排序这个vector内的元素。请注意在排序这些元素时,HasPtr的swap被调用的时机。
.cpp
#include<string>#include<vector>#include<algorithm>#include<iterator>#include"HasPtr.h"using namespace std;int main() { HasPtr hp,hp1("孙守真"),hp2(string("阿弥陀佛")),hp3("净空老法师"),hp4("海贤老和尚"),hp5("阿弥陀佛"); vector<HasPtr>vhp{hp,hp1,hp2,hp3,hp4,hp5}; ostream_iterator<string>o(cout, ","); for (HasPtr hp : vhp) o++=hp.getStr() ; std::cout<< std::endl; sort(vhp.begin(), vhp.end()); for (HasPtr hp : vhp) o++ = hp.getStr(); std::cout << std::endl;}
HasPtr.h
#ifndef HASPTR_H#define HASPTR_H#include<string>#include<iostream>class HasPtr{ friend void swap(HasPtr&, HasPtr&);public: HasPtr(const std::string& s = std::string()) : ps(new std::string(s)), i(0) {} //拷贝建构器:每个HasPtr物件都有一个ps指标指向的那个string的副本 HasPtr(const HasPtr& p) : ps(new std::string(*p.ps)), i(p.i) {} HasPtr& operator=(HasPtr); bool operator<(const HasPtr&); std::string& getStr(); ~HasPtr() { delete ps; } private: std::string* ps; int i;};inline void swap(HasPtr&lhs,HasPtr&rhs){//页517 using std::swap; swap(lhs.ps, rhs.ps); swap(lhs.i, rhs.i); std::cout << "swap here!感恩感恩 南无阿弥陀佛" << std::endl;}inline HasPtr& HasPtr::operator=(HasPtr rhs) {//页518 swap(rhs, *this); return *this;}inline bool HasPtr::operator<(const HasPtr& rhs) { if ((*ps < *rhs.ps) && (i<=rhs.i)) { return true; } return false;}inline std::string& HasPtr::getStr() { return *ps;}#endif // !HASPTR_H
https://github.com/oscarsun72/prog1-C-Primer-5th-Edition-s-Exercises/tree/exercise13_31_HasPtr_swap_sort/prog1
脸书直播
C++自修入门实境秀 547 重新译撰 《C++ Primer 5th》
13.3 swap对调 练习13.31~
上一集:
https://www.facebook.com/oscarsun72/videos/2668054499972334/
下一集:
全部:http://bit.ly/2NoA2ID 原档下载:http://bit.ly/2Ixe2Vc
课文: http://bit.ly/2FIHV57
http://bit.ly/2mttmfa(第二篇)
第10-11章: http://bit.ly/2MuPmiZ
章12: http://bit.ly/2Rw53sH
重译12章:http://bit.ly/2V8UgZ7
http://bit.ly/2G2fPSg (docx)
重译11章:http://bit.ly/39P7HRU
第三篇:http://bit.ly/2UaFbDY
第三篇13章:http://bit.ly/33mh49y
https://play.google.com/books/reader?id=J1HMLyxqJfgC&pg=GBS.PT957.w.1.0.57
讲义下载:
http://bit.ly/2khF8Ic (全部)
程式码:
https://github.com/oscarsun72/prog1
缘起:http://bit.ly/2XwHOUH