C++ Primer 5th Edition Exercises(練習題)13.31

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
.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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#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

臉書直播

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