Skip to content

Commit

Permalink
polished 13.31
Browse files Browse the repository at this point in the history
  • Loading branch information
Mooophy committed Jul 21, 2015
1 parent 519d7f5 commit 1e96061
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 27 deletions.
29 changes: 13 additions & 16 deletions ch13/ex13_31.cpp
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
//
// ex13_31
// Exercise 13.31
// Created by Soyn on 21/7/15.
// Add the vector<HasPtr>, and sort it.
// ex13_31
// Exercise 13.31
// Created by Soyn on 21/7/15.
// Add the vector<HasPtr>, and sort it.
//
#include<vector>
#include<algorithm>
// Refactored by Yue Wang Jul 2015
//
#include <vector>
#include <algorithm>
#include "ex13_31.h"

int main(void)
{
std :: vector< HasPtr> vh;
std :: string s1("s"), s2("a"),s3("c");
HasPtr h1(s1),h2(s2),h3(s3);
vh.push_back(h1);
vh.push_back(h2);
vh.push_back(h3);
sort(vh.begin(), vh.end());
for( auto e : vh){
e.show();
}
HasPtr s{ "s" }, a{ "a" }, c{ "c" };
std::vector<HasPtr> vec{ s, a, c };
std::sort(vec.begin(), vec.end());

for (auto const& elem : vec) elem.show();
return 0;
}
37 changes: 26 additions & 11 deletions ch13/ex13_31.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,42 +3,57 @@
// Exercise 13.31
//
// Created by pezy on 1/23/15.
// Copyright (c) 2015 pezy. All rights reserved.
//
// 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.
//
// See ex13_30.h
// Refactored by Yue Wang Jul 2015
//

#ifndef CP5_ex13_11_h
#define CP5_ex13_11_h

#include <string>
#include <iostream>

class HasPtr {
class HasPtr
{
public:
friend void swap(HasPtr&, HasPtr&);
friend bool operator<(const HasPtr &lhs, const HasPtr &rhs);
HasPtr(const std::string &s = std::string()) : ps(new std::string(s)), i(0) { }
HasPtr(const HasPtr &hp) : ps(new std::string(*hp.ps)), i(hp.i) { }
HasPtr& operator=(HasPtr tmp) {

HasPtr(const std::string &s = std::string())
: ps(new std::string(s)), i(0)
{ }

HasPtr(const HasPtr &hp)
: ps(new std::string(*hp.ps)), i(hp.i)
{ }

HasPtr& operator=(HasPtr tmp)
{
this->swap(tmp);
return *this;
}
~HasPtr() {

~HasPtr()
{
delete ps;
}

void swap(HasPtr &rhs) {

void swap(HasPtr &rhs)
{
using std::swap;
swap(ps, rhs.ps);
swap(i, rhs.i);
std::cout << "call swap(HasPtr &rhs)" << std::endl;
}

void show() { std::cout << *ps << std::endl; }

void show() const
{
std::cout << *ps << std::endl;
}
private:
std::string *ps;
int i;
Expand Down

0 comments on commit 1e96061

Please sign in to comment.