10000 test 13.3 swap() · tthhee/leetcode@3118ff6 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3118ff6

Browse files
committed
test 13.3 swap()
1 parent 19ab23f commit 3118ff6

File tree

2 files changed

+48
-5
lines changed

2 files changed

+48
-5
lines changed

C++PrimerTest/exercise13.2

46.7 KB
Binary file not shown.

C++PrimerTest/exercise13.2.cpp

Lines changed: 48 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,46 @@
11
#include <iostream>
22
#include <string>
33
#include <memory>
4+
#include <vector>
5+
#include <algorithm>
46

57
using namespace std;
68
//定义行为像值的类
79
class HasPtr
810
{
911
private:
10-
int i;
1112
string* ps;
13+
int i;
14+
1215
public:
13-
HasPtr(const string& s = string()):
14-
ps(new string(s)), i(0){}
15-
HasPtr(HasPtr& s):
16+
HasPtr(const string& s = string(), int a = 0):
17+
ps(new string(s)), i(a){}
18+
HasPtr(const HasPtr& s):
1619
ps(new string(*s.ps)), i(s.i){}
1720
HasPtr& operator=(const HasPtr& p);
21+
friend bool lessthan(const HasPtr& s1, const HasPtr& s2);
22+
friend ostream& operator<<(ostream& os, const HasPtr& P);
23+
friend void swap(HasPtr& , HasPtr&);
1824
~HasPtr()
1925
{
2026
delete ps;
2127
}
2228
};
23-
29+
bool lessthan(const HasPtr& s1, const HasPtr& s2)
30+
{
31+
if(s1.i < s2.i)
32+
{
33+
return true;
34+
}
35+
else
36+
{
37+
return false;
38+
}
39+
}
40+
ostream& operator<<(ostream& os, const HasPtr& p)
41+
{
42+
os << *p.ps << " " << p.i;
43+
}
2444
HasPtr& HasPtr::operator=(const HasPtr& p)
2545
{
2646
i = p.i;
@@ -30,6 +50,13 @@ HasPtr& HasPtr::operator=(const HasPtr& p)
3050
return *this;
3151
}
3252

53+
inline void swap(HasPtr& lsh, HasPtr& rsh)
54+
{
55+
using std::swap;
56+
swap(lsh.ps, rsh.ps);
57+
swap(lsh.i, rsh.i);
58+
cout << "using swap()" << endl;
59+
}
3360
//定义行为像指针的类
3461
class PHasPtr
3562
{
@@ -104,5 +131,21 @@ class TreeNode
104131
};
105132
int main()
106133
{
134+
HasPtr a("xiangyu", 2);
135+
HasPtr b("liuchang", 1);
136+
HasPtr c("liuzheng", 3);
137+
swap(a, b);
138+
cout << "a: " << a << endl;
139+
cout << "b: " << b << endl;
140+
vector<HasPtr> HasVec;
141+
HasVec.push_back(a);
142+
HasVec.push_back(b);
143+
HasVec.push_back(c);
144+
sort(HasVec.begin(), HasVec.end(), lessthan);
145+
for(auto it : HasVec)
146+
{
147+
cout << it << endl;
148+
}
149+
107150
return 0;
108151
}

0 commit comments

Comments
 (0)
0