diff --git a/.clang-format b/.clang-format index 97118325..12e25bfb 100644 --- a/.clang-format +++ b/.clang-format @@ -1,7 +1,7 @@ --- Language: Cpp # BasedOnStyle: LLVM -AccessModifierOffset: 0 +AccessModifierOffset: -4 AlignAfterOpenBracket: true AlignEscapedNewlinesLeft: false AlignOperands: true @@ -12,7 +12,7 @@ AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false AllowShortIfStatementsOnASingleLine: true AllowShortLoopsOnASingleLine: true -AllowShortFunctionsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Inline AlwaysBreakAfterDefinitionReturnType: false AlwaysBreakTemplateDeclarations: false AlwaysBreakBeforeMultilineStrings: false @@ -41,7 +41,7 @@ PenaltyBreakString: 1000 PenaltyBreakFirstLessLess: 120 PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 60 -PointerAlignment: Right +PointerAlignment: Left SpacesBeforeTrailingComments: 1 Cpp11BracedListStyle: true Standard: Cpp11 diff --git a/ch02/ex2_34.cpp b/ch02/ex2_34.cpp index 158c68f8..e65e4f32 100644 --- a/ch02/ex2_34.cpp +++ b/ch02/ex2_34.cpp @@ -12,7 +12,7 @@ int main() auto e = &ci; // e is const int*(& of a const object is low-level const) const auto f = ci; // deduced type of ci is int; f has type const int - auto &g = ci; // g is a const int& that is bound to ci + auto& g = ci; // g is a const int& that is bound to ci a = 42; b = 42; diff --git a/ch02/ex2_35.cpp b/ch02/ex2_35.cpp index 071878c2..a30e3dc6 100644 --- a/ch02/ex2_35.cpp +++ b/ch02/ex2_35.cpp @@ -5,9 +5,9 @@ int main() { const int i = 42; auto j = i; - const auto &k = i; - auto *p = &i; - const auto j2 = i, &k2 = i; + const auto& k = i; + auto* p = &i; + const auto j2 = i, & k2 = i; // print i means int, and PKi means pointer to const int. std::cout << "j is " << typeid(j).name() << "\nk is " << typeid(k).name() diff --git a/ch03/ex3_06.cpp b/ch03/ex3_06.cpp index 0938c1c5..c8927149 100644 --- a/ch03/ex3_06.cpp +++ b/ch03/ex3_06.cpp @@ -10,7 +10,7 @@ using std::endl; int main() { string str("a simple string"); - for (auto &c : str) c = 'X'; + for (auto& c : str) c = 'X'; cout << str << endl; return 0; diff --git a/ch03/ex3_17.cpp b/ch03/ex3_17.cpp index f1729806..28c1438d 100644 --- a/ch03/ex3_17.cpp +++ b/ch03/ex3_17.cpp @@ -24,8 +24,8 @@ int main() string word; while (cin >> word) vec.push_back(word); - for (auto &str : vec) - for (auto &c : str) c = toupper(c); + for (auto& str : vec) + for (auto& c : str) c = toupper(c); for (decltype(vec.size()) i = 0; i != vec.size(); ++i) { if (i != 0 && i % 8 == 0) cout << endl; diff --git a/ch03/ex3_21.cpp b/ch03/ex3_21.cpp index b5d14a9d..96a40b3e 100644 --- a/ch03/ex3_21.cpp +++ b/ch03/ex3_21.cpp @@ -12,7 +12,7 @@ using std::string; using std::cout; using std::endl; -void check(const vector &vec) +void check(const vector& vec) { if (vec.empty()) cout << "size: 0; no values." << endl; @@ -23,7 +23,7 @@ void check(const vector &vec) } } -void check(const vector &vec) +void check(const vector& vec) { if (vec.empty()) cout << "size: 0; no values." << endl; diff --git a/ch03/ex3_22.cpp b/ch03/ex3_22.cpp index cb972e4f..7cfbac09 100644 --- a/ch03/ex3_22.cpp +++ b/ch03/ex3_22.cpp @@ -22,7 +22,7 @@ int main() for (string line; getline(cin, line);) text.push_back(line); for (auto it = text.begin(); it != text.end() && !it->empty(); ++it) { - for (auto &c : *it) c = toupper(c); + for (auto& c : *it) c = toupper(c); cout << *it << endl; } diff --git a/ch03/ex3_35.cpp b/ch03/ex3_35.cpp index b9b4a389..86e72759 100644 --- a/ch03/ex3_35.cpp +++ b/ch03/ex3_35.cpp @@ -9,10 +9,10 @@ using std::endl; int main() { int arr[10]; - int *b = begin(arr); - int *e = end(arr); + int* b = begin(arr); + int* e = end(arr); - for (int *i = b; i != e; ++i) *i = 0; + for (int* i = b; i != e; ++i) *i = 0; for (auto i : arr) cout << i << " "; cout << endl; diff --git a/ch03/ex3_36.cpp b/ch03/ex3_36.cpp index 0057cba0..c229915f 100644 --- a/ch03/ex3_36.cpp +++ b/ch03/ex3_36.cpp @@ -9,7 +9,7 @@ using std::endl; using std::vector; // pb point to begin of the array, pe point to end of the array. -bool compare(int *const pb1, int *const pe1, int *const pb2, int *const pe2) +bool compare(int* const pb1, int* const pe1, int* const pb2, int* const pe2) { if ((pe1 - pb1) != (pe2 - pb2)) // have different size. return false; diff --git a/ch03/ex3_39.cpp b/ch03/ex3_39.cpp index eb274252..7e32e483 100644 --- a/ch03/ex3_39.cpp +++ b/ch03/ex3_39.cpp @@ -21,8 +21,8 @@ int main() cout << "=========" << endl; // use C-Style character strings. - const char *cs1 = "Wangyue"; - const char *cs2 = "Pezy"; + const char* cs1 = "Wangyue"; + const char* cs2 = "Pezy"; auto result = strcmp(cs1, cs2); if (result == 0) diff --git a/ch03/ex3_42.cpp b/ch03/ex3_42.cpp index 457f5acf..fb7037a4 100644 --- a/ch03/ex3_42.cpp +++ b/ch03/ex3_42.cpp @@ -12,7 +12,7 @@ int main() vector ivec{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int int_arr[10]; - for (int *i = begin(int_arr); i != end(int_arr); ++i) + for (int* i = begin(int_arr); i != end(int_arr); ++i) *i = ivec[i - begin(int_arr)]; for (auto i : int_arr) cout << i << " "; diff --git a/ch03/ex3_43.cpp b/ch03/ex3_43.cpp index 71e98277..92a9f291 100644 --- a/ch03/ex3_43.cpp +++ b/ch03/ex3_43.cpp @@ -19,7 +19,7 @@ int main() // using pointers. for (int(*p)[4] = ia; p != ia + 3; ++p) - for (int *q = *p; q != *p + 4; ++q) cout << *q << " "; + for (int* q = *p; q != *p + 4; ++q) cout << *q << " "; cout << endl; return 0; diff --git a/ch03/ex3_44.cpp b/ch03/ex3_44.cpp index 2f06733f..b31571b8 100644 --- a/ch03/ex3_44.cpp +++ b/ch03/ex3_44.cpp @@ -10,7 +10,7 @@ int main() // a range for to manage the iteration // use type alias using int_array = int[4]; - for (int_array &p : ia) + for (int_array& p : ia) for (int q : p) cout << q << " "; cout << endl; @@ -21,8 +21,8 @@ int main() // using pointers. // use type alias - for (int_array *p = ia; p != ia + 3; ++p) - for (int *q = *p; q != *p + 4; ++q) cout << *q << " "; + for (int_array* p = ia; p != ia + 3; ++p) + for (int* q = *p; q != *p + 4; ++q) cout << *q << " "; cout << endl; return 0; diff --git a/ch03/ex3_45.cpp b/ch03/ex3_45.cpp index 1ed67b41..11b96ef3 100644 --- a/ch03/ex3_45.cpp +++ b/ch03/ex3_45.cpp @@ -8,7 +8,7 @@ int main() int ia[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; // a range for to manage the iteration - for (auto &p : ia) + for (auto& p : ia) for (int q : p) cout << q << " "; cout << endl; @@ -19,7 +19,7 @@ int main() // using pointers. for (auto p = ia; p != ia + 3; ++p) - for (int *q = *p; q != *p + 4; ++q) cout << *q << " "; + for (int* q = *p; q != *p + 4; ++q) cout << *q << " "; cout << endl; return 0; diff --git a/ch04/ex4_21.cpp b/ch04/ex4_21.cpp index 02e3e138..dcf51532 100644 --- a/ch04/ex4_21.cpp +++ b/ch04/ex4_21.cpp @@ -4,7 +4,7 @@ int main() { std::vector ivec{1, 2, 3, 4, 5, 6, 7, 8, 9}; - for (auto &i : ivec) i = (i % 2) ? (i * 2) : i; + for (auto& i : ivec) i = (i % 2) ? (i * 2) : i; // Check for (auto i : ivec) std::cout << i << " "; diff --git a/ch06/ex6_10.cpp b/ch06/ex6_10.cpp index d118f382..251fa407 100644 --- a/ch06/ex6_10.cpp +++ b/ch06/ex6_10.cpp @@ -8,7 +8,7 @@ #include #include -void swap(int *lhs, int *rhs) +void swap(int* lhs, int* rhs) { int tmp; tmp = *lhs; diff --git a/ch06/ex6_11.cpp b/ch06/ex6_11.cpp index 09a30616..0e20bd9d 100644 --- a/ch06/ex6_11.cpp +++ b/ch06/ex6_11.cpp @@ -1,6 +1,6 @@ #include -void reset(int &i) +void reset(int& i) { i = 0; } diff --git a/ch06/ex6_12.cpp b/ch06/ex6_12.cpp index 1abbd5a6..d442f86f 100644 --- a/ch06/ex6_12.cpp +++ b/ch06/ex6_12.cpp @@ -9,7 +9,7 @@ #include #include -void swap(int &lhs, int &rhs) +void swap(int& lhs, int& rhs) { int temp = lhs; lhs = rhs; diff --git a/ch06/ex6_17.cpp b/ch06/ex6_17.cpp index fbba7455..d01c5bb4 100644 --- a/ch06/ex6_17.cpp +++ b/ch06/ex6_17.cpp @@ -5,16 +5,16 @@ using std::cout; using std::endl; using std::string; -bool hasUppercase(const string &str) +bool hasUppercase(const string& str) { for (auto c : str) if (isupper(c)) return true; return false; } -void makeLowercase(string &str) +void makeLowercase(string& str) { - for (auto &c : str) + for (auto& c : str) if (isupper(c)) c = tolower(c); } diff --git a/ch06/ex6_21.cpp b/ch06/ex6_21.cpp index 96a73ee9..5be53b5e 100644 --- a/ch06/ex6_21.cpp +++ b/ch06/ex6_21.cpp @@ -9,7 +9,7 @@ #include using std::cout; -int LargerOne(const int i, const int *ip) +int LargerOne(const int i, const int* ip) { return (i > *ip) ? i : *ip; } diff --git a/ch06/ex6_22.cpp b/ch06/ex6_22.cpp index a6443a74..91bfdd9e 100644 --- a/ch06/ex6_22.cpp +++ b/ch06/ex6_22.cpp @@ -5,7 +5,7 @@ //! #include -void swap(int *&lft, int *&rht) +void swap(int*& lft, int*& rht) { auto tmp = lft; lft = rht; diff --git a/ch06/ex6_23.cpp b/ch06/ex6_23.cpp index ad1d36b1..a3960c20 100644 --- a/ch06/ex6_23.cpp +++ b/ch06/ex6_23.cpp @@ -5,19 +5,19 @@ using std::endl; using std::begin; using std::end; -void print(const int *pi) +void print(const int* pi) { if (pi) cout << *pi << endl; } -void print(const char *p) +void print(const char* p) { if (p) while (*p) cout << *p++; cout << endl; } -void print(const int *beg, const int *end) +void print(const int* beg, const int* end) { while (beg != end) cout << *beg++ << endl; } diff --git a/ch06/ex6_25_26.cpp b/ch06/ex6_25_26.cpp index 061176b6..5405f4ca 100644 --- a/ch06/ex6_25_26.cpp +++ b/ch06/ex6_25_26.cpp @@ -10,7 +10,7 @@ #include #include -int main(int argc, char **argv) +int main(int argc, char** argv) { std::string str; for (int i = 1; i != argc; ++i) str += argv[i] + " "; diff --git a/ch06/ex6_42.cpp b/ch06/ex6_42.cpp index 8523c661..843602e6 100644 --- a/ch06/ex6_42.cpp +++ b/ch06/ex6_42.cpp @@ -12,7 +12,7 @@ using std::string; using std::cout; using std::endl; -string make_plural(size_t ctr, const string &word, const string &ending = "s") +string make_plural(size_t ctr, const string& word, const string& ending = "s") { return (ctr > 1) ? word + ending : word; } diff --git a/ch06/ex6_44.cpp b/ch06/ex6_44.cpp index a4601d27..8dfec775 100644 --- a/ch06/ex6_44.cpp +++ b/ch06/ex6_44.cpp @@ -9,7 +9,7 @@ using std::string; -inline bool isShorter(const string &s1, const string &s2) +inline bool isShorter(const string& s1, const string& s2) { return s1.size() < s2.size(); } diff --git a/ch06/ex6_47.cpp b/ch06/ex6_47.cpp index 0f893e3e..e2bb7c39 100644 --- a/ch06/ex6_47.cpp +++ b/ch06/ex6_47.cpp @@ -14,7 +14,7 @@ using std::endl; #define NDEBUG -void printVec(vector &vec) +void printVec(vector& vec) { #ifdef NDEBUG cout << "vector size: " << vec.size() << endl; diff --git a/ch06/ex6_54_55_56.cpp b/ch06/ex6_54_55_56.cpp index 9df066d5..0cc022e2 100644 --- a/ch06/ex6_54_55_56.cpp +++ b/ch06/ex6_54_55_56.cpp @@ -48,7 +48,7 @@ inline int NumDiv(const int n1, const int n2) return n1 / n2; } -vector v{NumAdd, NumSub, NumMul, NumDiv}; +vector v{NumAdd, NumSub, NumMul, NumDiv}; int main() { diff --git a/ch07/ex7_05.h b/ch07/ex7_05.h index 150d952d..946e1117 100644 --- a/ch07/ex7_05.h +++ b/ch07/ex7_05.h @@ -14,6 +14,7 @@ class Person { std::string name; std::string address; + public: const std::string& getName() const { return name; } const std::string& getAddress() const { return address; } @@ -23,5 +24,7 @@ class Person { // Should these functions be const? -// Yes, A const following the parameter list indicates that this is a pointer to const. -// These functions my read but not write to the data members of the objects on which it is called. +// Yes, A const following the parameter list indicates that this is a pointer to +// const. +// These functions my read but not write to the data members of the objects on +// which it is called. diff --git a/ch07/ex7_06.h b/ch07/ex7_06.h index 3a0de6e8..0a4eb316 100644 --- a/ch07/ex7_06.h +++ b/ch07/ex7_06.h @@ -30,7 +30,7 @@ Sales_data& Sales_data::combine(const Sales_data& rhs) } // nonmember functions -std::istream &read(std::istream &is, Sales_data &item) +std::istream& read(std::istream& is, Sales_data& item) { double price = 0; is >> item.bookNo >> item.units_sold >> price; @@ -38,13 +38,13 @@ std::istream &read(std::istream &is, Sales_data &item) return is; } -std::ostream &print(std::ostream &os, const Sales_data &item) +std::ostream& print(std::ostream& os, const Sales_data& item) { os << item.isbn() << " " << item.units_sold << " " << item.revenue; return os; } -Sales_data add(const Sales_data &lhs, const Sales_data &rhs) +Sales_data add(const Sales_data& lhs, const Sales_data& rhs) { Sales_data sum = lhs; sum.combine(rhs); diff --git a/ch07/ex7_07.cpp b/ch07/ex7_07.cpp index 715c1831..e9c057d3 100644 --- a/ch07/ex7_07.cpp +++ b/ch07/ex7_07.cpp @@ -11,8 +11,7 @@ int main() { Sales_data total; - if (read(std::cin, total)) - { + if (read(std::cin, total)) { Sales_data trans; while (read(std::cin, trans)) { if (total.isbn() == trans.isbn()) @@ -24,11 +23,10 @@ int main() } print(std::cout, total) << std::endl; } - else - { + else { std::cerr << "No data?!" << std::endl; return -1; } - + return 0; } diff --git a/ch07/ex7_09.h b/ch07/ex7_09.h index 6a1941a5..08365d15 100644 --- a/ch07/ex7_09.h +++ b/ch07/ex7_09.h @@ -20,14 +20,14 @@ struct Person { std::string address; }; -std::istream &read(std::istream &is, Person &person) +std::istream& read(std::istream& is, Person& person) { is >> person.name >> person.address; if (!is) person = Person(); return is; } -std::ostream &print(std::ostream &os, const Person &person) +std::ostream& print(std::ostream& os, const Person& person) { os << person.name << " " << person.address; return os; diff --git a/ch07/ex7_11.cpp b/ch07/ex7_11.cpp index 5695e135..43666bce 100644 --- a/ch07/ex7_11.cpp +++ b/ch07/ex7_11.cpp @@ -12,15 +12,15 @@ int main() { Sales_data item1; print(std::cout, item1) << std::endl; - + Sales_data item2("0-201-78345-X"); print(std::cout, item2) << std::endl; - + Sales_data item3("0-201-78345-X", 3, 20.00); print(std::cout, item3) << std::endl; - + Sales_data item4(std::cin); print(std::cout, item4) << std::endl; - + return 0; } diff --git a/ch07/ex7_11.h b/ch07/ex7_11.h index 7cc8e0a8..8c221d49 100644 --- a/ch07/ex7_11.h +++ b/ch07/ex7_11.h @@ -14,20 +14,23 @@ struct Sales_data { Sales_data() = default; - Sales_data(const std::string &s):bookNo(s) {} - Sales_data(const std::string &s, unsigned n, double p):bookNo(s),units_sold(n),revenue(n*p){} - Sales_data(std::istream &is); - + Sales_data(const std::string& s) : bookNo(s) {} + Sales_data(const std::string& s, unsigned n, double p) + : bookNo(s), units_sold(n), revenue(n * p) + { + } + Sales_data(std::istream& is); + std::string isbn() const { return bookNo; }; Sales_data& combine(const Sales_data&); - + std::string bookNo; unsigned units_sold = 0; double revenue = 0.0; }; // nonmember functions -std::istream &read(std::istream &is, Sales_data &item) +std::istream& read(std::istream& is, Sales_data& item) { double price = 0; is >> item.bookNo >> item.units_sold >> price; @@ -35,13 +38,13 @@ std::istream &read(std::istream &is, Sales_data &item) return is; } -std::ostream &print(std::ostream &os, const Sales_data &item) +std::ostream& print(std::ostream& os, const Sales_data& item) { os << item.isbn() << " " << item.units_sold << " " << item.revenue; return os; } -Sales_data add(const Sales_data &lhs, const Sales_data &rhs) +Sales_data add(const Sales_data& lhs, const Sales_data& rhs) { Sales_data sum = lhs; sum.combine(rhs); @@ -49,7 +52,7 @@ Sales_data add(const Sales_data &lhs, const Sales_data &rhs) } // member functions. -Sales_data::Sales_data(std::istream &is) +Sales_data::Sales_data(std::istream& is) { read(is, *this); } diff --git a/ch07/ex7_12.h b/ch07/ex7_12.h index d41fb98f..b659c9a6 100644 --- a/ch07/ex7_12.h +++ b/ch07/ex7_12.h @@ -13,17 +13,20 @@ #include struct Sales_data; -std::istream &read(std::istream&, Sales_data&); +std::istream& read(std::istream&, Sales_data&); struct Sales_data { Sales_data() = default; - Sales_data(const std::string &s):bookNo(s) {} - Sales_data(const std::string &s, unsigned n, double p):bookNo(s),units_sold(n),revenue(n*p){} - Sales_data(std::istream &is) { read(is, *this);} - + Sales_data(const std::string& s) : bookNo(s) {} + Sales_data(const std::string& s, unsigned n, double p) + : bookNo(s), units_sold(n), revenue(n * p) + { + } + Sales_data(std::istream& is) { read(is, *this); } + std::string isbn() const { return bookNo; }; Sales_data& combine(const Sales_data&); - + std::string bookNo; unsigned units_sold = 0; double revenue = 0.0; @@ -38,7 +41,7 @@ Sales_data& Sales_data::combine(const Sales_data& rhs) } // nonmember functions -std::istream &read(std::istream &is, Sales_data &item) +std::istream& read(std::istream& is, Sales_data& item) { double price = 0; is >> item.bookNo >> item.units_sold >> price; @@ -46,13 +49,13 @@ std::istream &read(std::istream &is, Sales_data &item) return is; } -std::ostream &print(std::ostream &os, const Sales_data &item) +std::ostream& print(std::ostream& os, const Sales_data& item) { os << item.isbn() << " " << item.units_sold << " " << item.revenue; return os; } -Sales_data add(const Sales_data &lhs, const Sales_data &rhs) +Sales_data add(const Sales_data& lhs, const Sales_data& rhs) { Sales_data sum = lhs; sum.combine(rhs); diff --git a/ch07/ex7_13.cpp b/ch07/ex7_13.cpp index 7c6139a7..71020e30 100644 --- a/ch07/ex7_13.cpp +++ b/ch07/ex7_13.cpp @@ -11,9 +11,8 @@ int main() { Sales_data total(std::cin); - if (!total.isbn().empty()) - { - std::istream &is = std::cin; + if (!total.isbn().empty()) { + std::istream& is = std::cin; while (is) { Sales_data trans(is); if (total.isbn() == trans.isbn()) @@ -24,11 +23,10 @@ int main() } } } - else - { + else { std::cerr << "No data?!" << std::endl; return -1; } - + return 0; } diff --git a/ch07/ex7_15.h b/ch07/ex7_15.h index e2da5083..9799289e 100644 --- a/ch07/ex7_15.h +++ b/ch07/ex7_15.h @@ -13,27 +13,30 @@ #include struct Person; -std::istream &read(std::istream&, Person&); +std::istream& read(std::istream&, Person&); struct Person { Person() = default; - Person(const std::string sname, const std::string saddr):name(sname), address(saddr){} - Person(std::istream &is){read(is, *this);} - + Person(const std::string sname, const std::string saddr) + : name(sname), address(saddr) + { + } + Person(std::istream& is) { read(is, *this); } + std::string getName() const { return name; } std::string getAddress() const { return address; } - + std::string name; std::string address; }; -std::istream &read(std::istream &is, Person &person) +std::istream& read(std::istream& is, Person& person) { is >> person.name >> person.address; return is; } -std::ostream &print(std::ostream &os, const Person &person) +std::ostream& print(std::ostream& os, const Person& person) { os << person.name << " " << person.address; return os; diff --git a/ch07/ex7_21.h b/ch07/ex7_21.h index 7a2082d9..1acc7cb8 100644 --- a/ch07/ex7_21.h +++ b/ch07/ex7_21.h @@ -13,15 +13,18 @@ #include class Sales_data { - friend std::istream &read(std::istream &is, Sales_data &item); - friend std::ostream &print(std::ostream &os, const Sales_data &item); - friend Sales_data add(const Sales_data &lhs, const Sales_data &rhs); + friend std::istream& read(std::istream& is, Sales_data& item); + friend std::ostream& print(std::ostream& os, const Sales_data& item); + friend Sales_data add(const Sales_data& lhs, const Sales_data& rhs); public: Sales_data() = default; - Sales_data(const std::string &s):bookNo(s) {} - Sales_data(const std::string &s, unsigned n, double p):bookNo(s),units_sold(n),revenue(n*p){} - Sales_data(std::istream &is) { read(is, *this);} + Sales_data(const std::string& s) : bookNo(s) {} + Sales_data(const std::string& s, unsigned n, double p) + : bookNo(s), units_sold(n), revenue(n * p) + { + } + Sales_data(std::istream& is) { read(is, *this); } std::string isbn() const { return bookNo; }; Sales_data& combine(const Sales_data&); @@ -41,7 +44,7 @@ Sales_data& Sales_data::combine(const Sales_data& rhs) } // friend functions -std::istream &read(std::istream &is, Sales_data &item) +std::istream& read(std::istream& is, Sales_data& item) { double price = 0; is >> item.bookNo >> item.units_sold >> price; @@ -49,13 +52,13 @@ std::istream &read(std::istream &is, Sales_data &item) return is; } -std::ostream &print(std::ostream &os, const Sales_data &item) +std::ostream& print(std::ostream& os, const Sales_data& item) { os << item.isbn() << " " << item.units_sold << " " << item.revenue; return os; } -Sales_data add(const Sales_data &lhs, const Sales_data &rhs) +Sales_data add(const Sales_data& lhs, const Sales_data& rhs) { Sales_data sum = lhs; sum.combine(rhs); diff --git a/ch07/ex7_22.h b/ch07/ex7_22.h index 13976f49..2435070b 100644 --- a/ch07/ex7_22.h +++ b/ch07/ex7_22.h @@ -13,13 +13,16 @@ #include struct Person { - friend std::istream &read(std::istream &is, Person &person); - friend std::ostream &print(std::ostream &os, const Person &person); + friend std::istream& read(std::istream& is, Person& person); + friend std::ostream& print(std::ostream& os, const Person& person); public: Person() = default; - Person(const std::string sname, const std::string saddr):name(sname), address(saddr){} - Person(std::istream &is){read(is, *this);} + Person(const std::string sname, const std::string saddr) + : name(sname), address(saddr) + { + } + Person(std::istream& is) { read(is, *this); } std::string getName() const { return name; } std::string getAddress() const { return address; } @@ -28,13 +31,13 @@ struct Person { std::string address; }; -std::istream &read(std::istream &is, Person &person) +std::istream& read(std::istream& is, Person& person) { is >> person.name >> person.address; return is; } -std::ostream &print(std::ostream &os, const Person &person) +std::ostream& print(std::ostream& os, const Person& person) { os << person.name << " " << person.address; return os; diff --git a/ch07/ex7_23.h b/ch07/ex7_23.h index 832fe776..351088f7 100644 --- a/ch07/ex7_23.h +++ b/ch07/ex7_23.h @@ -12,19 +12,21 @@ #include class Screen { - public: - using pos = std::string::size_type; +public: + using pos = std::string::size_type; - Screen() = default; - Screen(pos ht, pos wd, char c):height(ht),width(wd),contents(ht*wd, c){} + Screen() = default; + Screen(pos ht, pos wd, char c) : height(ht), width(wd), contents(ht * wd, c) + { + } - char get() const { return contents[cursor]; } - char get(pos r, pos c) const { return contents[r*width+c]; } + char get() const { return contents[cursor]; } + char get(pos r, pos c) const { return contents[r * width + c]; } - private: - pos cursor = 0; - pos height = 0, width = 0; - std::string contents; +private: + pos cursor = 0; + pos height = 0, width = 0; + std::string contents; }; #endif diff --git a/ch07/ex7_24.h b/ch07/ex7_24.h index 48c5ab33..a3466498 100644 --- a/ch07/ex7_24.h +++ b/ch07/ex7_24.h @@ -12,20 +12,22 @@ #include class Screen { - public: - using pos = std::string::size_type; +public: + using pos = std::string::size_type; - Screen() = default; // 1 - Screen(pos ht, pos wd):height(ht),width(wd),contents(ht*wd, ' '){} // 2 - Screen(pos ht, pos wd, char c):height(ht),width(wd),contents(ht*wd, c){} // 3 + Screen() = default; // 1 + Screen(pos ht, pos wd) : height(ht), width(wd), contents(ht * wd, ' ') {} // 2 + Screen(pos ht, pos wd, char c) : height(ht), width(wd), contents(ht * wd, c) + { + } // 3 - char get() const { return contents[cursor]; } - char get(pos r, pos c) const { return contents[r*width+c]; } + char get() const { return contents[cursor]; } + char get(pos r, pos c) const { return contents[r * width + c]; } - private: - pos cursor = 0; - pos height = 0, width = 0; - std::string contents; +private: + pos cursor = 0; + pos height = 0, width = 0; + std::string contents; }; #endif diff --git a/ch07/ex7_26.cpp b/ch07/ex7_26.cpp index 60c9ebea..e4947b7a 100644 --- a/ch07/ex7_26.cpp +++ b/ch07/ex7_26.cpp @@ -19,7 +19,7 @@ Sales_data& Sales_data::combine(const Sales_data& rhs) } // friend functions -std::istream &read(std::istream &is, Sales_data &item) +std::istream& read(std::istream& is, Sales_data& item) { double price = 0; is >> item.bookNo >> item.units_sold >> price; @@ -27,13 +27,13 @@ std::istream &read(std::istream &is, Sales_data &item) return is; } -std::ostream &print(std::ostream &os, const Sales_data &item) +std::ostream& print(std::ostream& os, const Sales_data& item) { os << item.isbn() << " " << item.units_sold << " " << item.revenue; return os; } -Sales_data add(const Sales_data &lhs, const Sales_data &rhs) +Sales_data add(const Sales_data& lhs, const Sales_data& rhs) { Sales_data sum = lhs; sum.combine(rhs); diff --git a/ch07/ex7_26.h b/ch07/ex7_26.h index 6d69d250..71ccd186 100644 --- a/ch07/ex7_26.h +++ b/ch07/ex7_26.h @@ -6,7 +6,7 @@ // Copyright (c) 2014 pezy. All rights reserved. // // @See ex7_21.h -// @Add inline member function "Sales_data::avg_pric" +// @Add inline member function "Sales_data::avg_pric" #ifndef CP5_ex7_26_h #define CP5_ex7_26_h @@ -15,21 +15,24 @@ #include class Sales_data { - friend std::istream &read(std::istream &is, Sales_data &item); - friend std::ostream &print(std::ostream &os, const Sales_data &item); - friend Sales_data add(const Sales_data &lhs, const Sales_data &rhs); + friend std::istream& read(std::istream& is, Sales_data& item); + friend std::ostream& print(std::ostream& os, const Sales_data& item); + friend Sales_data add(const Sales_data& lhs, const Sales_data& rhs); public: Sales_data() = default; - Sales_data(const std::string &s):bookNo(s) {} - Sales_data(const std::string &s, unsigned n, double p):bookNo(s),units_sold(n),revenue(n*p){} - Sales_data(std::istream &is) { read(is, *this); } + Sales_data(const std::string& s) : bookNo(s) {} + Sales_data(const std::string& s, unsigned n, double p) + : bookNo(s), units_sold(n), revenue(n * p) + { + } + Sales_data(std::istream& is) { read(is, *this); } std::string isbn() const { return bookNo; }; Sales_data& combine(const Sales_data&); - + private: - inline double avg_price() const; + inline double avg_price() const; private: std::string bookNo; @@ -37,15 +40,14 @@ class Sales_data { double revenue = 0.0; }; -inline -double Sales_data::avg_price() const +inline double Sales_data::avg_price() const { - return units_sold ? revenue/units_sold : 0; + return units_sold ? revenue / units_sold : 0; } // declarations for nonmember parts of the Sales_data interface. -std::istream &read(std::istream &is, Sales_data &item); -std::ostream &print(std::ostream &os, const Sales_data &item); -Sales_data add(const Sales_data &lhs, const Sales_data &rhs); +std::istream& read(std::istream& is, Sales_data& item); +std::ostream& print(std::ostream& os, const Sales_data& item); +Sales_data add(const Sales_data& lhs, const Sales_data& rhs); #endif diff --git a/ch07/ex7_27.h b/ch07/ex7_27.h index 00eccbf3..a25484a6 100644 --- a/ch07/ex7_27.h +++ b/ch07/ex7_27.h @@ -17,20 +17,30 @@ class Screen { using pos = std::string::size_type; Screen() = default; // 1 - Screen(pos ht, pos wd):height(ht),width(wd),contents(ht*wd, ' '){} // 2 - Screen(pos ht, pos wd, char c):height(ht),width(wd),contents(ht*wd, c){} // 3 + Screen(pos ht, pos wd) : height(ht), width(wd), contents(ht * wd, ' ') {} // 2 + Screen(pos ht, pos wd, char c) : height(ht), width(wd), contents(ht * wd, c) + { + } // 3 char get() const { return contents[cursor]; } - char get(pos r, pos c) const { return contents[r*width+c]; } + char get(pos r, pos c) const { return contents[r * width + c]; } inline Screen& move(pos r, pos c); inline Screen& set(char c); inline Screen& set(pos r, pos c, char ch); - const Screen& display(std::ostream &os) const { do_display(os); return *this; } - Screen& display(std::ostream &os) { do_display(os); return *this; } + const Screen& display(std::ostream& os) const + { + do_display(os); + return *this; + } + Screen& display(std::ostream& os) + { + do_display(os); + return *this; + } private: - void do_display(std::ostream &os) const { os << contents; } + void do_display(std::ostream& os) const { os << contents; } private: pos cursor = 0; @@ -40,7 +50,7 @@ class Screen { inline Screen& Screen::move(pos r, pos c) { - cursor = r*width + c; + cursor = r * width + c; return *this; } @@ -52,7 +62,7 @@ inline Screen& Screen::set(char c) inline Screen& Screen::set(pos r, pos c, char ch) { - contents[r*width+c] = ch; + contents[r * width + c] = ch; return *this; } diff --git a/ch07/ex7_32.h b/ch07/ex7_32.h index e5090892..c0869b12 100644 --- a/ch07/ex7_32.h +++ b/ch07/ex7_32.h @@ -1,6 +1,6 @@ // // ex7_32.h -// Exercise 7.32 +// Exercise 7.32 // // Created by pezy on 11/18/14. // Copyright (c) 2014 pezy. All rights reserved. @@ -20,30 +20,42 @@ class Window_mgr { public: using ScreenIndex = std::vector::size_type; inline void clear(ScreenIndex); + private: std::vector screens; }; class Screen { friend void Window_mgr::clear(ScreenIndex); + public: using pos = std::string::size_type; Screen() = default; // 1 - Screen(pos ht, pos wd):height(ht),width(wd),contents(ht*wd, ' '){} // 2 - Screen(pos ht, pos wd, char c):height(ht),width(wd),contents(ht*wd, c){} // 3 + Screen(pos ht, pos wd) : height(ht), width(wd), contents(ht * wd, ' ') {} // 2 + Screen(pos ht, pos wd, char c) : height(ht), width(wd), contents(ht * wd, c) + { + } // 3 char get() const { return contents[cursor]; } - char get(pos r, pos c) const { return contents[r*width+c]; } + char get(pos r, pos c) const { return contents[r * width + c]; } inline Screen& move(pos r, pos c); inline Screen& set(char c); inline Screen& set(pos r, pos c, char ch); - const Screen& display(std::ostream &os) const { do_display(os); return *this; } - Screen& display(std::ostream &os) { do_display(os); return *this; } + const Screen& display(std::ostream& os) const + { + do_display(os); + return *this; + } + Screen& display(std::ostream& os) + { + do_display(os); + return *this; + } private: - void do_display(std::ostream &os) const { os << contents; } + void do_display(std::ostream& os) const { os << contents; } private: pos cursor = 0; @@ -52,15 +64,15 @@ class Screen { }; inline void Window_mgr::clear(ScreenIndex i) -{ - if (i >= screens.size()) return; // judge for out_of_range. - Screen &s = screens[i]; +{ + if (i >= screens.size()) return; // judge for out_of_range. + Screen& s = screens[i]; s.contents = std::string(s.height * s.width, ' '); } inline Screen& Screen::move(pos r, pos c) { - cursor = r*width + c; + cursor = r * width + c; return *this; } @@ -72,7 +84,7 @@ inline Screen& Screen::set(char c) inline Screen& Screen::set(pos r, pos c, char ch) { - contents[r*width+c] = ch; + contents[r * width + c] = ch; return *this; } diff --git a/ch07/ex7_41.cpp b/ch07/ex7_41.cpp index 3cb267e7..e1ab63d5 100644 --- a/ch07/ex7_41.cpp +++ b/ch07/ex7_41.cpp @@ -11,7 +11,7 @@ #include "ex7_41.h" // constructor -Sales_data::Sales_data(std::istream &is) : Sales_data() +Sales_data::Sales_data(std::istream& is) : Sales_data() { std::cout << "Sales_data(istream &is)" << std::endl; read(is, *this); @@ -26,7 +26,7 @@ Sales_data& Sales_data::combine(const Sales_data& rhs) } // friend functions -std::istream &read(std::istream &is, Sales_data &item) +std::istream& read(std::istream& is, Sales_data& item) { double price = 0; is >> item.bookNo >> item.units_sold >> price; @@ -34,13 +34,13 @@ std::istream &read(std::istream &is, Sales_data &item) return is; } -std::ostream &print(std::ostream &os, const Sales_data &item) +std::ostream& print(std::ostream& os, const Sales_data& item) { os << item.isbn() << " " << item.units_sold << " " << item.revenue; return os; } -Sales_data add(const Sales_data &lhs, const Sales_data &rhs) +Sales_data add(const Sales_data& lhs, const Sales_data& rhs) { Sales_data sum = lhs; sum.combine(rhs); diff --git a/ch07/ex7_41.h b/ch07/ex7_41.h index 2c584691..091b0c7a 100644 --- a/ch07/ex7_41.h +++ b/ch07/ex7_41.h @@ -1,13 +1,14 @@ // // ex7_41.h -// Exercise 7.41 +// Exercise 7.41 // // Created by pezy on 11/20/14. // Copyright (c) 2014 pezy. All rights reserved. // // @See ex7_26.h // @Add 1. use delegating constructors -// 2. add a statement to the body of each of the constructors that prints a message whether it is executed. +// 2. add a statement to the body of each of the constructors that prints +// a message whether it is executed. #ifndef CP5_ex7_41_h #define CP5_ex7_41_h @@ -16,27 +17,35 @@ #include class Sales_data { - friend std::istream &read(std::istream &is, Sales_data &item); - friend std::ostream &print(std::ostream &os, const Sales_data &item); - friend Sales_data add(const Sales_data &lhs, const Sales_data &rhs); + friend std::istream& read(std::istream& is, Sales_data& item); + friend std::ostream& print(std::ostream& os, const Sales_data& item); + friend Sales_data add(const Sales_data& lhs, const Sales_data& rhs); public: - Sales_data(const std::string &s, unsigned n, double p):bookNo(s),units_sold(n),revenue(n*p) - { std::cout << "Sales_data(const std::string&, unsigned, double)" << std::endl; } - + Sales_data(const std::string& s, unsigned n, double p) + : bookNo(s), units_sold(n), revenue(n * p) + { + std::cout << "Sales_data(const std::string&, unsigned, double)" + << std::endl; + } + Sales_data() : Sales_data("", 0, 0.0f) - { std::cout << "Sales_data()" << std::endl; } - - Sales_data(const std::string &s) : Sales_data(s, 0, 0.0f) - { std::cout << "Sales_data(const std::string&)" << std::endl; } - - Sales_data(std::istream &is); + { + std::cout << "Sales_data()" << std::endl; + } + + Sales_data(const std::string& s) : Sales_data(s, 0, 0.0f) + { + std::cout << "Sales_data(const std::string&)" << std::endl; + } + + Sales_data(std::istream& is); std::string isbn() const { return bookNo; } Sales_data& combine(const Sales_data&); - + private: - inline double avg_price() const; + inline double avg_price() const; private: std::string bookNo; @@ -44,15 +53,14 @@ class Sales_data { double revenue = 0.0; }; -inline -double Sales_data::avg_price() const +inline double Sales_data::avg_price() const { - return units_sold ? revenue/units_sold : 0; + return units_sold ? revenue / units_sold : 0; } // declarations for nonmember parts of the Sales_data interface. -std::istream &read(std::istream &is, Sales_data &item); -std::ostream &print(std::ostream &os, const Sales_data &item); -Sales_data add(const Sales_data &lhs, const Sales_data &rhs); +std::istream& read(std::istream& is, Sales_data& item); +std::ostream& print(std::ostream& os, const Sales_data& item); +Sales_data add(const Sales_data& lhs, const Sales_data& rhs); #endif diff --git a/ch07/ex7_41_TEST.cpp b/ch07/ex7_41_TEST.cpp index 64a8ca43..587388c6 100644 --- a/ch07/ex7_41_TEST.cpp +++ b/ch07/ex7_41_TEST.cpp @@ -7,49 +7,50 @@ // #include "ex7_41.h" -using std::cout; using std::endl; +using std::cout; +using std::endl; int main() { cout << "1. default way: " << endl; cout << "----------------" << endl; - Sales_data s1; - + Sales_data s1; + cout << "\n2. use std::string as parameter: " << endl; cout << "----------------" << endl; Sales_data s2("CPP-Primer-5th"); - + cout << "\n3. complete parameters: " << endl; cout << "----------------" << endl; Sales_data s3("CPP-Primer-5th", 3, 25.8); - + cout << "\n4. use istream as parameter: " << endl; cout << "----------------" << endl; Sales_data s4(std::cin); - + return 0; } -// print +// print /* * 1. default way: * ---------------- * Sales_data(const std::string&, unsigned, double) * Sales_data() - * + * * 2. use std::string as parameter: * ---------------- * Sales_data(const std::string&, unsigned, double) * Sales_data(const std::string&) - * + * * 3. complete parameters: * ---------------- * Sales_data(const std::string&, unsigned, double) - * + * * 4. use istream as parameter: * ---------------- * Sales_data(const std::string&, unsigned, double) * Sales_data() * Sales_data(istream &is) * - */ + */ diff --git a/ch07/ex7_43.cpp b/ch07/ex7_43.cpp index bd2c11be..6a32f89d 100644 --- a/ch07/ex7_43.cpp +++ b/ch07/ex7_43.cpp @@ -6,16 +6,16 @@ // Copyright (c) 2014 pezy. All rights reserved. // -#include +#include class NoDefault { public: - NoDefault(int i) { } + NoDefault(int i) {} }; class C { public: - C() : def(0) { } // define the constructor of C. + C() : def(0) {} // define the constructor of C. private: NoDefault def; }; @@ -23,7 +23,7 @@ class C { int main() { C c; - - std::vector vec(10); + + std::vector vec(10); return 0; } diff --git a/ch07/ex7_50.h b/ch07/ex7_50.h index 94ee2a13..a7c95c02 100644 --- a/ch07/ex7_50.h +++ b/ch07/ex7_50.h @@ -15,13 +15,16 @@ #include struct Person { - friend std::istream &read(std::istream &is, Person &person); - friend std::ostream &print(std::ostream &os, const Person &person); + friend std::istream& read(std::istream& is, Person& person); + friend std::ostream& print(std::ostream& os, const Person& person); public: Person() = default; - Person(const std::string sname, const std::string saddr):name(sname), address(saddr){} - explicit Person(std::istream &is){read(is, *this);} + Person(const std::string sname, const std::string saddr) + : name(sname), address(saddr) + { + } + explicit Person(std::istream& is) { read(is, *this); } std::string getName() const { return name; } std::string getAddress() const { return address; } @@ -30,17 +33,16 @@ struct Person { std::string address; }; -std::istream &read(std::istream &is, Person &person) +std::istream& read(std::istream& is, Person& person) { is >> person.name >> person.address; return is; } -std::ostream &print(std::ostream &os, const Person &person) +std::ostream& print(std::ostream& os, const Person& person) { os << person.name << " " << person.address; return os; } #endif - diff --git a/ch07/ex7_53.h b/ch07/ex7_53.h index b88a828f..313033dc 100644 --- a/ch07/ex7_53.h +++ b/ch07/ex7_53.h @@ -11,18 +11,18 @@ class Debug { public: - constexpr Debug(bool b = true) : rt(b), io(b), other(b) { } - constexpr Debug(bool r, bool i, bool o) : rt(r), io(i), other(0) { } + constexpr Debug(bool b = true) : rt(b), io(b), other(b) {} + constexpr Debug(bool r, bool i, bool o) : rt(r), io(i), other(0) {} constexpr bool any() { return rt || io || other; } - + void set_rt(bool b) { rt = b; } void set_io(bool b) { io = b; } void set_other(bool b) { other = b; } - + private: - bool rt; // runtime error - bool io; // I/O error - bool other; // the others + bool rt; // runtime error + bool io; // I/O error + bool other; // the others }; #endif diff --git a/ch07/ex7_57.h b/ch07/ex7_57.h index 87214b68..33be81f0 100644 --- a/ch07/ex7_57.h +++ b/ch07/ex7_57.h @@ -16,7 +16,7 @@ class Account { void calculate() { amount += amount * interestRate; } static double rate() { return interestRate; } static void rate(double newRate) { interestRate = newRate; } - + private: std::string owner; double amount; diff --git a/ch08/ex8_02.cpp b/ch08/ex8_02.cpp index 35e78dfd..a72f5643 100644 --- a/ch08/ex8_02.cpp +++ b/ch08/ex8_02.cpp @@ -10,11 +10,10 @@ #include using std::istream; -istream& func(istream &is) +istream& func(istream& is) { std::string buf; - while (is >> buf) - std::cout << buf << std::endl; + while (is >> buf) std::cout << buf << std::endl; is.clear(); return is; } diff --git a/ch08/ex8_04.cpp b/ch08/ex8_04.cpp index 01430f04..61fe8777 100644 --- a/ch08/ex8_04.cpp +++ b/ch08/ex8_04.cpp @@ -5,24 +5,27 @@ // Created by pezy on 11/9/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief Write a function to open a file for input and read its contents into a vector of strings, -// storing each line as a separate element in the vector. +// @Brief Write a function to open a file for input and read its contents into +// a vector of strings, +// storing each line as a separate element in the vector. #include #include #include #include -using std::vector; using std::string; using std::ifstream; using std::cout; using std::endl; +using std::vector; +using std::string; +using std::ifstream; +using std::cout; +using std::endl; void ReadFileToVec(const string& fileName, vector& vec) { ifstream ifs(fileName); - if (ifs) - { + if (ifs) { string buf; - while (std::getline(ifs, buf)) - vec.push_back(buf); + while (std::getline(ifs, buf)) vec.push_back(buf); } } @@ -30,8 +33,6 @@ int main() { vector vec; ReadFileToVec("../data/book.txt", vec); - for (const auto &str : vec) - cout << str << endl; + for (const auto& str : vec) cout << str << endl; return 0; } - diff --git a/ch08/ex8_05.cpp b/ch08/ex8_05.cpp index b54658e3..05c37681 100644 --- a/ch08/ex8_05.cpp +++ b/ch08/ex8_05.cpp @@ -5,24 +5,27 @@ // Created by pezy on 11/9/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief Rewrite the previous program to store each word in a separate element. -// @See ex8_04.cpp +// @Brief Rewrite the previous program to store each word in a separate +// element. +// @See ex8_04.cpp #include #include #include #include -using std::vector; using std::string; using std::ifstream; using std::cout; using std::endl; +using std::vector; +using std::string; +using std::ifstream; +using std::cout; +using std::endl; void ReadFileToVec(const string& fileName, vector& vec) { ifstream ifs(fileName); - if (ifs) - { + if (ifs) { string buf; - while (ifs >> buf) - vec.push_back(buf); + while (ifs >> buf) vec.push_back(buf); } } @@ -30,8 +33,6 @@ int main() { vector vec; ReadFileToVec("../data/book.txt", vec); - for (const auto &str : vec) - cout << str << endl; + for (const auto& str : vec) cout << str << endl; return 0; } - diff --git a/ch08/ex8_06.cpp b/ch08/ex8_06.cpp index afd0023c..a9cd752a 100644 --- a/ch08/ex8_06.cpp +++ b/ch08/ex8_06.cpp @@ -5,43 +5,43 @@ // Created by pezy on 11/27/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief Rewrite the bookstore program from ¡ì7.1.1 (p.256) to read its transactions from a file. -// Pass the name of the file as an argument to main (¡ì6.2.5, p.218). +// @Brief Rewrite the bookstore program from ¡ì7.1.1 (p.256) to read its +// transactions from a file. +// Pass the name of the file as an argument to main (¡ì6.2.5, p.218). // @See ex7_26.h (use the Sales_data) // @Run give a parameter: "../data/book.txt" // @Output 0-201-78345-X 5 110 -// 0-201-78346-X 9 839.2 +// 0-201-78346-X 9 839.2 #include #include #include "../ch07/ex7_26.h" -using std::ifstream; using std::cout; using std::endl; using std::cerr; +using std::ifstream; +using std::cout; +using std::endl; +using std::cerr; -int main(int argc, char **argv) +int main(int argc, char** argv) { ifstream input(argv[1]); - + Sales_data total; - if (read(input, total)) - { + if (read(input, total)) { Sales_data trans; - while (read(input, trans)) - { + while (read(input, trans)) { if (total.isbn() == trans.isbn()) total.combine(trans); - else - { + else { print(cout, total) << endl; total = trans; } } print(cout, total) << endl; } - else - { + else { cerr << "No data?!" << endl; } - + return 0; } diff --git a/ch08/ex8_07.cpp b/ch08/ex8_07.cpp index d9fa3939..33931659 100644 --- a/ch08/ex8_07.cpp +++ b/ch08/ex8_07.cpp @@ -5,7 +5,8 @@ // Created by pezy on 11/28/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief Revise the bookstore program from the previous section to write its output to a file. +// @Brief Revise the bookstore program from the previous section to write its +// output to a file. // Pass the name of that file as a second argument to main. // @See ex8_06.cpp // @Run give a parameter: "../data/book.txt ../data/out.txt" @@ -14,33 +15,32 @@ #include #include "../ch07/ex7_26.h" -using std::ifstream; using std::ofstream; using std::endl; using std::cerr; +using std::ifstream; +using std::ofstream; +using std::endl; +using std::cerr; -int main(int argc, char **argv) +int main(int argc, char** argv) { ifstream input(argv[1]); ofstream output(argv[2]); - + Sales_data total; - if (read(input, total)) - { + if (read(input, total)) { Sales_data trans; - while (read(input, trans)) - { + while (read(input, trans)) { if (total.isbn() == trans.isbn()) total.combine(trans); - else - { + else { print(output, total) << endl; total = trans; } } print(output, total) << endl; } - else - { + else { cerr << "No data?!" << endl; } - + return 0; } diff --git a/ch08/ex8_08.cpp b/ch08/ex8_08.cpp index 3747ddd4..be1b1663 100644 --- a/ch08/ex8_08.cpp +++ b/ch08/ex8_08.cpp @@ -5,8 +5,10 @@ // Created by pezy on 11/28/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief Revise the program from the previous exercise to append its output to its given file. -// Run the program on the same output file at least twice to ensure that the data are preserved +// @Brief Revise the program from the previous exercise to append its output +// to its given file. +// Run the program on the same output file at least twice to ensure +// that the data are preserved // @See ex8_07.cpp // @Run give a parameter: "../data/book.txt ../data/out.txt" @@ -14,33 +16,32 @@ #include #include "../ch07/ex7_26.h" -using std::ifstream; using std::ofstream; using std::endl; using std::cerr; +using std::ifstream; +using std::ofstream; +using std::endl; +using std::cerr; -int main(int argc, char **argv) +int main(int argc, char** argv) { ifstream input(argv[1]); ofstream output(argv[2], ofstream::app); - + Sales_data total; - if (read(input, total)) - { + if (read(input, total)) { Sales_data trans; - while (read(input, trans)) - { + while (read(input, trans)) { if (total.isbn() == trans.isbn()) total.combine(trans); - else - { + else { print(output, total) << endl; total = trans; } } print(output, total) << endl; } - else - { + else { cerr << "No data?!" << endl; } - + return 0; } diff --git a/ch08/ex8_09.cpp b/ch08/ex8_09.cpp index 2926d5dd..c6443fbb 100644 --- a/ch08/ex8_09.cpp +++ b/ch08/ex8_09.cpp @@ -5,18 +5,18 @@ // Created by pezy on 11/29/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief Use the function you wrote for the first exercise in § 8.1.2 (p.314) to print the contents of an istringstream object. +// @Brief Use the function you wrote for the first exercise in § 8.1.2 (p.314) +// to print the contents of an istringstream object. // @See Exercise 8.1 #include #include using std::istream; -istream& func(istream &is) +istream& func(istream& is) { std::string buf; - while (is >> buf) - std::cout << buf << std::endl; + while (is >> buf) std::cout << buf << std::endl; is.clear(); return is; } diff --git a/ch08/ex8_10.cpp b/ch08/ex8_10.cpp index 6b1a9f04..b1c1806d 100644 --- a/ch08/ex8_10.cpp +++ b/ch08/ex8_10.cpp @@ -6,7 +6,8 @@ // Copyright (c) 2014 pezy. All rights reserved. // // @Brief Write a program to store each line from a file in a vector. -// Now use an istringstream to read each element from the vector a word at a time. +// Now use an istringstream to read each element from the vector a word +// at a time. #include #include @@ -14,29 +15,31 @@ #include #include -using std::vector; using std::string; using std::ifstream; using std::istringstream; using std::cout; using std::endl; using std::cerr; +using std::vector; +using std::string; +using std::ifstream; +using std::istringstream; +using std::cout; +using std::endl; +using std::cerr; int main() { ifstream ifs("../data/book.txt"); - if (!ifs) - { + if (!ifs) { cerr << "No data?" << endl; return -1; } - + vector vecLine; string line; - while (getline(ifs, line)) - vecLine.push_back(line); - - for (auto &s : vecLine) - { + while (getline(ifs, line)) vecLine.push_back(line); + + for (auto& s : vecLine) { istringstream iss(s); string word; - while (iss >> word) - cout << word << endl; + while (iss >> word) cout << word << endl; } - + return 0; } diff --git a/ch08/ex8_11.cpp b/ch08/ex8_11.cpp index 56f545c3..194eca94 100644 --- a/ch08/ex8_11.cpp +++ b/ch08/ex8_11.cpp @@ -5,15 +5,22 @@ // Created by pezy on 11/29/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief The program in this section defined its istringstream object inside the outer while loop. -// What changes would you need to make if record were defined outside that loop? -// Rewrite the program, moving the definition of record outside the while, and see whether you thought of all the changes that are needed. +// @Brief The program in this section defined its istringstream object inside +// the outer while loop. +// What changes would you need to make if record were defined outside +// that loop? +// Rewrite the program, moving the definition of record outside the +// while, and see whether you thought of all the changes that are +// needed. #include #include #include #include -using std::vector; using std::string; using std::cin; using std::istringstream; +using std::vector; +using std::string; +using std::cin; +using std::istringstream; struct PersonInfo { string name; @@ -25,24 +32,20 @@ int main() string line, word; vector people; istringstream record; - while (getline(cin, line)) - { + while (getline(cin, line)) { PersonInfo info; record.clear(); record.str(line); record >> info.name; - while (record >> word) - info.phones.push_back(word); + while (record >> word) info.phones.push_back(word); people.push_back(info); } - - for (auto &p : people) - { + + for (auto& p : people) { std::cout << p.name << " "; - for (auto &s : p.phones) - std::cout << s << " "; + for (auto& s : p.phones) std::cout << s << " "; std::cout << std::endl; } - + return 0; } diff --git a/ch08/ex8_13.cpp b/ch08/ex8_13.cpp index a61d2f6a..cd69611a 100644 --- a/ch08/ex8_13.cpp +++ b/ch08/ex8_13.cpp @@ -15,8 +15,15 @@ #include #include -using std::vector; using std::string; using std::cin; using std::istringstream; -using std::ostringstream; using std::ifstream; using std::cerr; using std::cout; using std::endl; +using std::vector; +using std::string; +using std::cin; +using std::istringstream; +using std::ostringstream; +using std::ifstream; +using std::cerr; +using std::cout; +using std::endl; using std::isdigit; struct PersonInfo { @@ -31,14 +38,13 @@ bool valid(const string& str) string format(const string& str) { - return str.substr(0,3) + "-" + str.substr(3,3) + "-" + str.substr(6); + return str.substr(0, 3) + "-" + str.substr(3, 3) + "-" + str.substr(6); } int main() { ifstream ifs("../data/phonenumbers.txt"); - if (!ifs) - { + if (!ifs) { cerr << "no phone numbers?" << endl; return -1; } @@ -46,28 +52,27 @@ int main() string line, word; vector people; istringstream record; - while (getline(ifs, line)) - { + while (getline(ifs, line)) { PersonInfo info; record.clear(); record.str(line); record >> info.name; - while (record >> word) - info.phones.push_back(word); + while (record >> word) info.phones.push_back(word); people.push_back(info); } - for (const auto &entry : people) - { + for (const auto& entry : people) { ostringstream formatted, badNums; - for (const auto &nums : entry.phones) - if (!valid(nums)) badNums << " " << nums; - else formatted << " " << format(nums); + for (const auto& nums : entry.phones) + if (!valid(nums)) + badNums << " " << nums; + else + formatted << " " << format(nums); if (badNums.str().empty()) cout << entry.name << " " << formatted.str() << endl; else - cerr << "input error: " << entry.name - << " invalid number(s) " << badNums.str() << endl; + cerr << "input error: " << entry.name << " invalid number(s) " + << badNums.str() << endl; } return 0; diff --git a/ch09/ex9_13.cpp b/ch09/ex9_13.cpp index 03d5300c..b4c3f54b 100644 --- a/ch09/ex9_13.cpp +++ b/ch09/ex9_13.cpp @@ -10,7 +10,10 @@ #include #include -using std::list; using std::vector; using std::cout; using std::endl; +using std::list; +using std::vector; +using std::cout; +using std::endl; int main() { @@ -18,21 +21,17 @@ int main() vector ivc(5, 5); //! from list to vector - vector dvc(ilst.begin(),ilst.end()); - for (auto i : ilst) - cout << i; + vector dvc(ilst.begin(), ilst.end()); + for (auto i : ilst) cout << i; cout << endl; - for (auto t : dvc) - cout << t; + for (auto t : dvc) cout << t; cout << endl; //! from vector to vector vector dvc2(ivc.begin(), ivc.end()); - for (auto i : ivc) - cout << i; + for (auto i : ivc) cout << i; cout << endl; - for (auto t : dvc2) - cout << t; + for (auto t : dvc2) cout << t; return 0; } diff --git a/ch09/ex9_14.cpp b/ch09/ex9_14.cpp index 3a96e155..d399c442 100644 --- a/ch09/ex9_14.cpp +++ b/ch09/ex9_14.cpp @@ -18,8 +18,7 @@ int main() std::vector v; v.assign(l.cbegin(), l.cend()); - for (const auto &ch : v) - std::cout << ch << std::endl; + for (const auto& ch : v) std::cout << ch << std::endl; return 0; } diff --git a/ch09/ex9_16.cpp b/ch09/ex9_16.cpp index 05de2963..c6cf5a2f 100644 --- a/ch09/ex9_16.cpp +++ b/ch09/ex9_16.cpp @@ -1,7 +1,8 @@ //! @file Exercise 9.16 //! @author pezy //! @date 2014-12-02 -//! @Brief Repeat the previous program, but compare elements in a list to a vector. +//! @Brief Repeat the previous program, but compare elements in a list to +//! a vector. #include #include @@ -13,6 +14,10 @@ int main() std::vector vec1{1, 2, 3, 4, 5}; std::vector vec2{1, 2, 3, 4}; - std::cout << std::boolalpha << (std::vector(list.begin(), list.end()) == vec1) << std::endl; - std::cout << std::boolalpha << (std::vector(list.begin(), list.end()) == vec2) << std::endl; + std::cout << std::boolalpha + << (std::vector(list.begin(), list.end()) == vec1) + << std::endl; + std::cout << std::boolalpha + << (std::vector(list.begin(), list.end()) == vec2) + << std::endl; } diff --git a/ch09/ex9_18.cpp b/ch09/ex9_18.cpp index a078cb85..b6c8c51b 100644 --- a/ch09/ex9_18.cpp +++ b/ch09/ex9_18.cpp @@ -5,19 +5,26 @@ // Created by pezy on 12/3/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief Write a program to read a sequence of strings from the standard input into -// a deque. Use iterators to write a loop to print the elements in the deque. +// @Brief Write a program to read a sequence of strings from the standard +// input into +// a deque. Use iterators to write a loop to print the elements in the +// deque. #include #include #include -using std::string; using std::deque; using std::cout; using std::cin; using std::endl; +using std::string; +using std::deque; +using std::cout; +using std::cin; +using std::endl; int main() { deque input; - for (string str; cin >> str; input.push_back(str)); + for (string str; cin >> str; input.push_back(str)) + ; for (auto iter = input.cbegin(); iter != input.cend(); ++iter) cout << *iter << endl; diff --git a/ch09/ex9_19.cpp b/ch09/ex9_19.cpp index 202421ec..7d87a1a4 100644 --- a/ch09/ex9_19.cpp +++ b/ch09/ex9_19.cpp @@ -13,12 +13,17 @@ #include #include -using std::string; using std::list; using std::cout; using std::cin; using std::endl; +using std::string; +using std::list; +using std::cout; +using std::cin; +using std::endl; int main() { list input; - for (string str; cin >> str; input.push_back(str)); + for (string str; cin >> str; input.push_back(str)) + ; for (auto iter = input.cbegin(); iter != input.cend(); ++iter) cout << *iter << endl; diff --git a/ch09/ex9_20.cpp b/ch09/ex9_20.cpp index 833b0118..b9e1bdcf 100644 --- a/ch09/ex9_20.cpp +++ b/ch09/ex9_20.cpp @@ -6,23 +6,27 @@ // Copyright (c) 2014 pezy. All rights reserved. // // @Brief Write a program to copy elements from a list into two deques. -// The even-valued elements should go into one deque and the odd ones into the other. +// The even-valued elements should go into one deque and the odd ones +// into the other. #include #include #include -using std::deque; using std::list; using std::cout; using std::cin; using std::endl; +using std::deque; +using std::list; +using std::cout; +using std::cin; +using std::endl; int main() { - list l{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + list l{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; deque odd, even; - for (auto i : l) - (i & 0x1 ? odd : even).push_back(i); + for (auto i : l) (i & 0x1 ? odd : even).push_back(i); for (auto i : odd) cout << i << " "; cout << endl; - for (auto i : even)cout << i << " "; + for (auto i : even) cout << i << " "; cout << endl; return 0; diff --git a/ch09/ex9_22.cpp b/ch09/ex9_22.cpp index 41ab13db..e3c83741 100644 --- a/ch09/ex9_22.cpp +++ b/ch09/ex9_22.cpp @@ -2,24 +2,24 @@ #include using std::vector; -void insertDoubleValue(vector &iv, int some_val) +void insertDoubleValue(vector& iv, int some_val) { auto cursor = iv.size() / 2; auto iter = iv.begin(), mid = iv.begin() + cursor; while (iter != mid) { if (*iter == some_val) { iter = iv.insert(iter, 2 * some_val); - ++iter; ++cursor; + ++iter; + ++cursor; mid = iv.begin() + cursor; } ++iter; } } -void print(const vector &iv) +void print(const vector& iv) { - for (auto i : iv) - std::cout << i << " "; + for (auto i : iv) std::cout << i << " "; std::cout << std::endl; } diff --git a/ch09/ex9_24.cpp b/ch09/ex9_24.cpp index dd7696b3..181c831e 100644 --- a/ch09/ex9_24.cpp +++ b/ch09/ex9_24.cpp @@ -2,7 +2,8 @@ //! //! Exercise 9.24: //! Write a program that fetches the first element in a vector using at, -//! the subscript operator, front, and begin. Test your program on an empty vector. +//! the subscript operator, front, and begin. Test your program on an empty +//! vector. //! #include #include @@ -10,9 +11,10 @@ int main() { std::vector v; - std::cout << v.at(0); // terminating with uncaught exception of type std::out_of_range - std::cout << v[0]; // Segmentation fault: 11 - std::cout << v.front(); // Segmentation fault: 11 - std::cout << *v.begin(); // Segmentation fault: 11 + std::cout << v.at( + 0); // terminating with uncaught exception of type std::out_of_range + std::cout << v[0]; // Segmentation fault: 11 + std::cout << v.front(); // Segmentation fault: 11 + std::cout << *v.begin(); // Segmentation fault: 11 return 0; } diff --git a/ch09/ex9_26.cpp b/ch09/ex9_26.cpp index 63e8e852..724242f2 100644 --- a/ch09/ex9_26.cpp +++ b/ch09/ex9_26.cpp @@ -4,38 +4,47 @@ //! //! Exercise 9.26: //! Using the following definition of ia, copy ia into a vector and into a list. -//! Use the single-iterator form of erase to remove the elements with odd values from your +//! Use the single-iterator form of erase to remove the elements with odd values +//! from your //! list and the even values from your vector. //! #include #include #include -using std::vector; using std::list; using std::cout; using std::endl; using std::end; +using std::vector; +using std::list; +using std::cout; +using std::endl; +using std::end; int main() { - int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 }; + int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89}; //! init vector vec(ia, end(ia)); list lst(vec.begin(), vec.end()); //! remove odd value - for(auto it = lst.begin(); it != lst.end(); ) - if(*it & 0x1) it = lst.erase(it); - else ++it; + for (auto it = lst.begin(); it != lst.end();) + if (*it & 0x1) + it = lst.erase(it); + else + ++it; //! remove even value - for(auto it = vec.begin(); it != vec.end(); ) - if(! (*it & 0x1)) it = vec.erase(it); - else ++it; + for (auto it = vec.begin(); it != vec.end();) + if (!(*it & 0x1)) + it = vec.erase(it); + else + ++it; //! print cout << "list : "; - for(auto i : lst) cout << i << " "; + for (auto i : lst) cout << i << " "; cout << "\nvector : "; - for(auto i : vec) cout << i << " "; + for (auto i : vec) cout << i << " "; cout << std::endl; return 0; diff --git a/ch09/ex9_27.cpp b/ch09/ex9_27.cpp index c9f4109a..6a181a43 100644 --- a/ch09/ex9_27.cpp +++ b/ch09/ex9_27.cpp @@ -1,21 +1,26 @@ //! @file Exercise 9.27 //! @author pezy //! @date 2014-12-03 -//! @Brief Write a program to find and remove the odd-valued elements in a forward_list. +//! @Brief Write a program to find and remove the odd-valued elements in a +//! forward_list. #include #include -using std::forward_list; using std::cout; using std::endl; +using std::forward_list; +using std::cout; +using std::endl; int main() { forward_list flst = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - for (auto prev = flst.before_begin(), curr = flst.begin(); curr != flst.end();) - if (*curr & 0x1) curr = flst.erase_after(prev); - else prev = curr++; + for (auto prev = flst.before_begin(), curr = flst.begin(); + curr != flst.end();) + if (*curr & 0x1) + curr = flst.erase_after(prev); + else + prev = curr++; - for (auto i : flst) - cout << i << " "; + for (auto i : flst) cout << i << " "; cout << endl; } diff --git a/ch09/ex9_31_1.cpp b/ch09/ex9_31_1.cpp index 7a222084..290cda90 100644 --- a/ch09/ex9_31_1.cpp +++ b/ch09/ex9_31_1.cpp @@ -1,37 +1,38 @@ // // ex9_31.cpp -// Exercise 9.31 +// Exercise 9.31 // // Created by pezy on 12/3/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief The program on page 354 to remove even-valued elements and -// duplicate odd ones will not work on a list or forward_list. Why? -// Revise the program so that it works on these types as well. +// @Brief The program on page 354 to remove even-valued elements and +// duplicate odd ones will not work on a list or forward_list. Why? +// Revise the program so that it works on these types as well. // @list iter += 2; -> advance(iter, 2); // #include #include -using std::list; using std::cout; using std::endl; using std::advance; +using std::list; +using std::cout; +using std::endl; +using std::advance; int main() { - list vi = {0,1,2,3,4,5,6,7,8,9}; - auto iter = vi.begin(); - while (iter != vi.end()) { - if (*iter % 2) { - iter = vi.insert(iter, *iter); - advance(iter, 2); - } else - iter = vi.erase(iter); + list vi = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + auto iter = vi.begin(); + while (iter != vi.end()) { + if (*iter % 2) { + iter = vi.insert(iter, *iter); + advance(iter, 2); + } + else + iter = vi.erase(iter); } - - for (auto i : vi) - cout << i << " "; - - return 0; -} + for (auto i : vi) cout << i << " "; + return 0; +} diff --git a/ch09/ex9_31_2.cpp b/ch09/ex9_31_2.cpp index feee634d..c6ef1788 100644 --- a/ch09/ex9_31_2.cpp +++ b/ch09/ex9_31_2.cpp @@ -1,13 +1,13 @@ // // ex9_31.cpp -// Exercise 9.31 +// Exercise 9.31 // // Created by pezy on 12/3/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief The program on page 354 to remove even-valued elements and -// duplicate odd ones will not work on a list or forward_list. Why? -// Revise the program so that it works on these types as well. +// @Brief The program on page 354 to remove even-valued elements and +// duplicate odd ones will not work on a list or forward_list. Why? +// Revise the program so that it works on these types as well. // @forward_list 1. vi.insert -> vi.insert_after // 2. iter += 2; -> advance(iter, 2); // 3. vi.erase -> vi.erase_after @@ -16,25 +16,26 @@ #include #include -using std::forward_list; using std::cout; using std::endl; using std::advance; +using std::forward_list; +using std::cout; +using std::endl; +using std::advance; int main() { - forward_list vi = {0,1,2,3,4,5,6,7,8,9}; + forward_list vi = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto iter = vi.begin(), prev = vi.before_begin(); - while (iter != vi.end()) { - if (*iter % 2) { - iter = vi.insert_after(prev, *iter); + while (iter != vi.end()) { + if (*iter % 2) { + iter = vi.insert_after(prev, *iter); advance(iter, 2); advance(prev, 2); - } else + } + else iter = vi.erase_after(prev); } - - for (auto i : vi) - cout << i << " "; - - return 0; -} + for (auto i : vi) cout << i << " "; + return 0; +} diff --git a/ch09/ex9_32.cpp b/ch09/ex9_32.cpp index 916cb2aa..eb6200d4 100644 --- a/ch09/ex9_32.cpp +++ b/ch09/ex9_32.cpp @@ -5,13 +5,15 @@ // Created by pezy on 12/3/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief In the program on page 354 would it be legal to write the call to insert as follows? +// @Brief In the program on page 354 would it be legal to write the call to +// insert as follows? // If not, why not? // iter = vi.insert(iter, *iter++); // @Answer the statement is illegal, cause as said in Standard [5.2.2] : // "The order of evaluation of arguments is unspecified." // As a result, after entering function insert, -// iter could be its original value or original value + 1 or even anything else, +// iter could be its original value or original value + 1 or even +// anything else, // depending on how compiler implemented. // correct it as follows: // @Discuss https://github.com/Mooophy/Cpp-Primer/issues/125 @@ -19,22 +21,24 @@ #include #include -using std::vector; using std::cout; using std::endl; +using std::vector; +using std::cout; +using std::endl; int main() { - vector vi = {0,1,2,3,4,5,6,7,8,9}; + vector vi = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto iter = vi.begin(); while (iter != vi.end()) { if (*iter % 2) { iter = vi.insert(iter, *iter); iter += 2; - } else + } + else iter = vi.erase(iter); } - for (auto i : vi) - cout << i << " "; + for (auto i : vi) cout << i << " "; return 0; } diff --git a/ch09/ex9_33.cpp b/ch09/ex9_33.cpp index 5f474663..3f763b51 100644 --- a/ch09/ex9_33.cpp +++ b/ch09/ex9_33.cpp @@ -1,35 +1,36 @@ // // ex9_33.cpp -// Exercise 9.33 +// Exercise 9.33 // // Created by pezy on 12/3/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief In the final example in this section what would happen -// if we did not assign the result of insert to begin? -// Write a program that omits this assignment to see if your expectation was correct. -// @Answer crash, cause the iterator is invalid after insert. Because Iterators, pointers, and references to a -// vector or string are invalid if the container was reallocated. +// @Brief In the final example in this section what would happen +// if we did not assign the result of insert to begin? +// Write a program that omits this assignment to see if your +// expectation was correct. +// @Answer crash, cause the iterator is invalid after insert. Because +// Iterators, pointers, and references to a +// vector or string are invalid if the container was reallocated. #include #include -using std::vector; using std::cout; using std::endl; +using std::vector; +using std::cout; +using std::endl; int main() { - vector v{1,2,3,4,5,6,7,8,9}; + vector v{1, 2, 3, 4, 5, 6, 7, 8, 9}; auto begin = v.begin(); while (begin != v.end()) { ++begin; - /*begin = */v.insert(begin, 42); + /*begin = */ v.insert(begin, 42); ++begin; - } - - for (auto i : v) - cout << i << " "; - - return 0; -} + } + for (auto i : v) cout << i << " "; + return 0; +} diff --git a/ch09/ex9_34.cpp b/ch09/ex9_34.cpp index d8df7fb6..adc9cd89 100644 --- a/ch09/ex9_34.cpp +++ b/ch09/ex9_34.cpp @@ -1,44 +1,46 @@ // // ex9_32.cpp -// Exercise 9.32 +// Exercise 9.32 // // Created by pezy on 12/3/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief Assuming vi is a container of ints that includes even and odd values, -// predict the behavior of the following loop. -// After you've analyzed this loop, write a program to test whether your expectations were correct. -// -// iter = vi.begin(); -// while (iter != vi.end()) -// if (*iter % 2) -// iter = vi.insert(iter, *iter); -// ++iter; +// @Brief Assuming vi is a container of ints that includes even and odd +// values, +// predict the behavior of the following loop. +// After you've analyzed this loop, write a program to test whether +// your expectations were correct. // -// @Answer "infinite loop". Casue the `++iter` out of the `while` loop. But even through add brackets it is still infinite loop. +// iter = vi.begin(); +// while (iter != vi.end()) +// if (*iter % 2) +// iter = vi.insert(iter, *iter); +// ++iter; +// +// @Answer "infinite loop". Casue the `++iter` out of the `while` loop. But +// even through add brackets it is still infinite loop. // Fixed following. #include -using std::cout; using std::endl; +using std::cout; +using std::endl; #include using std::vector; int main() { - vector vi = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - auto iter = vi.begin(); - while (iter != vi.end()) { - if (*iter % 2) { - iter = vi.insert(iter, *iter); - ++iter; - } - ++iter; - } + vector vi = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + auto iter = vi.begin(); + while (iter != vi.end()) { + if (*iter % 2) { + iter = vi.insert(iter, *iter); + ++iter; + } + ++iter; + } - for (auto i : vi) - cout << i << " "; + for (auto i : vi) cout << i << " "; - return 0; + return 0; } - diff --git a/ch09/ex9_38.cpp b/ch09/ex9_38.cpp index 71ca7409..863596c5 100644 --- a/ch09/ex9_38.cpp +++ b/ch09/ex9_38.cpp @@ -13,12 +13,10 @@ int main() std::vector v; std::string word; - while (std::cin >> word) - { + while (std::cin >> word) { v.push_back(word); std::cout << v.capacity() << "\n"; } return 0; } - diff --git a/ch09/ex9_41.cpp b/ch09/ex9_41.cpp index 70575e04..a0bbadc8 100644 --- a/ch09/ex9_41.cpp +++ b/ch09/ex9_41.cpp @@ -11,14 +11,17 @@ #include #include -using std::vector; using std::cout; using std::endl; using std::string; +using std::vector; +using std::cout; +using std::endl; +using std::string; int main() { vector vec{'p', 'e', 'z', 'y'}; string str(vec.begin(), vec.end()); - + cout << str << endl; - + return 0; } diff --git a/ch09/ex9_43.cpp b/ch09/ex9_43.cpp index 402f1c20..3d5ede7e 100644 --- a/ch09/ex9_43.cpp +++ b/ch09/ex9_43.cpp @@ -16,10 +16,13 @@ using std::string; #include -void Replace(string &s, const string &oldVal, const string &newVal) { +void Replace(string& s, const string& oldVal, const string& newVal) +{ for (auto beg = s.begin(); beg != s.end(); ++beg) { if (*beg != oldVal.front()) continue; - if (std::distance(beg, s.end()) < std::distance(oldVal.begin(), oldVal.end())) break; + if (std::distance(beg, s.end()) < + std::distance(oldVal.begin(), oldVal.end())) + break; if (string{beg, beg + oldVal.size()} == oldVal) { auto pos = std::distance(s.begin(), beg); s.erase(beg, beg + oldVal.size()); @@ -29,7 +32,8 @@ void Replace(string &s, const string &oldVal, const string &newVal) { } } -int main() { +int main() +{ { string str{"To drive straight thru is a foolish, tho courageous act."}; Replace(str, "thru", "through"); @@ -37,7 +41,8 @@ int main() { std::cout << str << std::endl; } { - string str{"To drive straight thruthru is a foolish, thotho courageous act."}; + string str{ + "To drive straight thruthru is a foolish, thotho courageous act."}; Replace(str, "thru", "through"); Replace(str, "tho", "though"); std::cout << str << std::endl; @@ -50,7 +55,8 @@ int main() { } { string str{"my world is a big world"}; - Replace(str, "world", "worldddddddddddddddddddddddddddddddddddddddddddddddd"); + Replace(str, "world", + "worldddddddddddddddddddddddddddddddddddddddddddddddd"); std::cout << str << std::endl; } return 0; diff --git a/ch09/ex9_44.cpp b/ch09/ex9_44.cpp index 3d94a356..451818e4 100644 --- a/ch09/ex9_44.cpp +++ b/ch09/ex9_44.cpp @@ -11,13 +11,16 @@ #include #include -using std::cout; using std::endl; using std::string; using std::prev; +using std::cout; +using std::endl; +using std::string; +using std::prev; void Replace(string& s, string const& oldVal, string const& newVal) { - for ( string::size_type i = 0; i != s.size(); ++i ) - if ( s.substr( i, oldVal.size() ) == oldVal ) { - s.replace( i, oldVal.size(), newVal ); + for (string::size_type i = 0; i != s.size(); ++i) + if (s.substr(i, oldVal.size()) == oldVal) { + s.replace(i, oldVal.size(), newVal); i += newVal.size() - 1; } } @@ -25,7 +28,7 @@ void Replace(string& s, string const& oldVal, string const& newVal) int main() { string str{"To drive straight thru is a foolish, tho courageous act."}; - Replace( str, "tho", "though" ); - Replace( str, "thru", "through" ); + Replace(str, "tho", "though"); + Replace(str, "thru", "through"); cout << str << endl; } diff --git a/ch09/ex9_45.cpp b/ch09/ex9_45.cpp index 3526e66f..08445a77 100644 --- a/ch09/ex9_45.cpp +++ b/ch09/ex9_45.cpp @@ -13,8 +13,8 @@ #include //! Exercise 9.45 -std::string -pre_suffix(const std::string &name, const std::string &pre, const std::string &su); +std::string pre_suffix(const std::string& name, const std::string& pre, + const std::string& su); int main() { @@ -24,9 +24,8 @@ int main() return 0; } - -inline std::string -pre_suffix(const std::string &name, const std::string &pre, const std::string &su) +inline std::string pre_suffix(const std::string& name, const std::string& pre, + const std::string& su) { auto ret = name; ret.insert(ret.begin(), pre.begin(), pre.end()); diff --git a/ch09/ex9_46.cpp b/ch09/ex9_46.cpp index b14bc87b..90f76901 100644 --- a/ch09/ex9_46.cpp +++ b/ch09/ex9_46.cpp @@ -5,19 +5,21 @@ // Created by pezy on 12/5/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief Rewrite the previous exercise using a position and length to manage the strings. +// @Brief Rewrite the previous exercise using a position and length to manage +// the strings. // This time use only the insert function. // @See 9.45 #include #include -std::string pre_suffix(const std::string &name, const std::string &pre, const std::string &su) +std::string pre_suffix(const std::string& name, const std::string& pre, + const std::string& su) { std::string ret(name); ret.insert(0, pre); ret.insert(ret.size(), su); - + return ret; } @@ -25,6 +27,6 @@ int main() { std::string name("alan"); std::cout << pre_suffix(name, "Mr.", ",Jr."); - + return 0; } diff --git a/ch09/ex9_47_1.cpp b/ch09/ex9_47_1.cpp index 2683eb62..6bf80066 100644 --- a/ch09/ex9_47_1.cpp +++ b/ch09/ex9_47_1.cpp @@ -7,28 +7,33 @@ // // @Brief Write a program that finds each numeric character // and then each alphabetic character in the string "ab2c3d7R4E6". -// Write two versions of the program. The first should use find_first_of, +// Write two versions of the program. The first should use +// find_first_of, // and the second find_first_not_of. // @Version find_first_of #include #include -using std::string; using std::cout; using std::endl; +using std::string; +using std::cout; +using std::endl; int main() { string numbers{"123456789"}; string alphabet{"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"}; string str{"ab2c3d7R4E6"}; - + cout << "numeric characters: "; - for (string::size_type pos = 0; (pos = str.find_first_of(numbers, pos)) != string::npos; ++pos) + for (string::size_type pos = 0; + (pos = str.find_first_of(numbers, pos)) != string::npos; ++pos) cout << str[pos] << " "; cout << "\nalphabetic characters: "; - for (string::size_type pos = 0; (pos = str.find_first_of(alphabet, pos)) != string::npos; ++pos) + for (string::size_type pos = 0; + (pos = str.find_first_of(alphabet, pos)) != string::npos; ++pos) cout << str[pos] << " "; cout << endl; - + return 0; } diff --git a/ch09/ex9_47_2.cpp b/ch09/ex9_47_2.cpp index 79eb9ab4..1b962f04 100644 --- a/ch09/ex9_47_2.cpp +++ b/ch09/ex9_47_2.cpp @@ -7,28 +7,33 @@ // // @Brief Write a program that finds each numeric character // and then each alphabetic character in the string "ab2c3d7R4E6". -// Write two versions of the program. The first should use find_first_of, +// Write two versions of the program. The first should use +// find_first_of, // and the second find_first_not_of. // @Version find_first_not_of #include #include -using std::string; using std::cout; using std::endl; +using std::string; +using std::cout; +using std::endl; int main() { string numbers{"123456789"}; string alphabet{"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"}; string str{"ab2c3d7R4E6"}; - + cout << "numeric characters: "; - for (string::size_type pos = 0; (pos = str.find_first_not_of(alphabet, pos)) != string::npos; ++pos) + for (string::size_type pos = 0; + (pos = str.find_first_not_of(alphabet, pos)) != string::npos; ++pos) cout << str[pos] << " "; cout << "\nalphabetic characters: "; - for (string::size_type pos = 0; (pos = str.find_first_not_of(numbers, pos)) != string::npos; ++pos) + for (string::size_type pos = 0; + (pos = str.find_first_not_of(numbers, pos)) != string::npos; ++pos) cout << str[pos] << " "; cout << endl; - + return 0; } diff --git a/ch09/ex9_49.cpp b/ch09/ex9_49.cpp index d826b93d..eb1d289e 100644 --- a/ch09/ex9_49.cpp +++ b/ch09/ex9_49.cpp @@ -1,18 +1,25 @@ //! @file Exercise 9.49 //! @author pezy //! @date 2014-12-05 -//! @Brief A letter has an ascender if, as with d or f, part of the letter extends above the middle of the line. -// A letter has a descender if, as with p or g, part of the letter extends below the line. -// Write a program that reads a file containing words and reports the longest word that contains +//! @Brief A letter has an ascender if, as with d or f, part of the letter +//! extends above the middle of the line. +// A letter has a descender if, as with p or g, part of the letter +// extends below the line. +// Write a program that reads a file containing words and reports the +// longest word that contains // neither ascenders nor descenders. #include #include #include -using std::string; using std::ifstream; using std::cout; using std::endl; +using std::string; +using std::ifstream; +using std::cout; +using std::endl; -int main() { +int main() +{ ifstream ifs("../data/letter.txt"); if (!ifs) return -1; string longest_word; diff --git a/ch09/ex9_50.cpp b/ch09/ex9_50.cpp index e293d83d..0391108f 100644 --- a/ch09/ex9_50.cpp +++ b/ch09/ex9_50.cpp @@ -1,9 +1,11 @@ //! @Yue Wang //! //! Exercise 9.50: -//! Write a program to process a vectors whose elements represent integral values. +//! Write a program to process a vectors whose elements represent +//! integral values. //! Produce the sum of all the elements in that vector. -//! Change the program so that it sums of strings that represent floating-point values. +//! Change the program so that it sums of strings that represent floating-point +//! values. //! #include @@ -13,22 +15,20 @@ int sum_for_int(const std::vector const& v) { int sum = 0; - for (auto const& s : v) - sum += std::stoi(s); + for (auto const& s : v) sum += std::stoi(s); return sum; } float sum_for_float(const std::vector const& v) { float sum = 0.0; - for (auto const& s : v) - sum += std::stof(s); + for (auto const& s : v) sum += std::stof(s); return sum; } int main() { - std::vector v = { "1", "2", "3", "4.5" }; + std::vector v = {"1", "2", "3", "4.5"}; std::cout << sum_for_int(v) << std::endl; std::cout << sum_for_float(v) << std::endl; diff --git a/ch09/ex9_51.cpp b/ch09/ex9_51.cpp index f725576f..efb0d0d1 100644 --- a/ch09/ex9_51.cpp +++ b/ch09/ex9_51.cpp @@ -11,10 +11,9 @@ #include #include -class wy_Date -{ +class wy_Date { public: - wy_Date(const std::string &s); + wy_Date(const std::string& s); unsigned year; unsigned month; unsigned day; @@ -24,58 +23,52 @@ int main() { wy_Date d("99/21/3871"); - std::cout << d.day <<" " - <= 4 && s.find_first_of(",") != std::string::npos) + if (s.find_first_of(",") >= 4 && s.find_first_of(",") != std::string::npos) format = 0x01; - switch (format) - { + switch (format) { //! format = 1/1/1900 - case 0x10: - day = std::stoi( s.substr(0, s.find_first_of("/"))); - month = std::stoi( s.substr(s.find_first_of("/") + 1, s.find_first_of("/") - s.find_last_of("/"))); - year = std::stoi( s.substr(s.find_last_of("/") + 1, 4)); + case 0x10: + day = std::stoi(s.substr(0, s.find_first_of("/"))); + month = std::stoi(s.substr(s.find_first_of("/") + 1, + s.find_first_of("/") - s.find_last_of("/"))); + year = std::stoi(s.substr(s.find_last_of("/") + 1, 4)); break; - - //! format = January 1, 1900 or Jan 1, 1900 - case 0x01: - day = std::stoi( s.substr(s.find_first_of("1234567890"), s.find_first_of(",") - s.find_first_of("1234567890" ))); - - if( s.find("Jan") < s.size() ) month = 1; - if( s.find("Feb") < s.size() ) month = 2; - if( s.find("Mar") < s.size() ) month = 3; - if( s.find("Apr") < s.size() ) month = 4; - if( s.find("May") < s.size() ) month = 5; - if( s.find("Jun") < s.size() ) month = 6; - if( s.find("Jul") < s.size() ) month = 7; - if( s.find("Aug") < s.size() ) month = 8; - if( s.find("Sep") < s.size() ) month = 9; - if( s.find("Oct") < s.size() ) month =10; - if( s.find("Nov") < s.size() ) month =11; - if( s.find("Dec") < s.size() ) month =12; - - year = std::stoi( s.substr(s.find_last_of(" ") + 1,4)); + case 0x01: + day = std::stoi( + s.substr(s.find_first_of("1234567890"), + s.find_first_of(",") - s.find_first_of("1234567890"))); + + if (s.find("Jan") < s.size()) month = 1; + if (s.find("Feb") < s.size()) month = 2; + if (s.find("Mar") < s.size()) month = 3; + if (s.find("Apr") < s.size()) month = 4; + if (s.find("May") < s.size()) month = 5; + if (s.find("Jun") < s.size()) month = 6; + if (s.find("Jul") < s.size()) month = 7; + if (s.find("Aug") < s.size()) month = 8; + if (s.find("Sep") < s.size()) month = 9; + if (s.find("Oct") < s.size()) month = 10; + if (s.find("Nov") < s.size()) month = 11; + if (s.find("Dec") < s.size()) month = 12; + + year = std::stoi(s.substr(s.find_last_of(" ") + 1, 4)); break; } - - - } diff --git a/ch09/ex9_52.cpp b/ch09/ex9_52.cpp index 831ea1d8..47f3354e 100644 --- a/ch09/ex9_52.cpp +++ b/ch09/ex9_52.cpp @@ -8,8 +8,10 @@ // @Brief Use a stack to process parenthesized expressions. // When you see an open parenthesis, note that it was seen. // When you see a close parenthesis after an open parenthesis, -// pop elements down to and including the open parenthesis off the stack. -// push a value onto the stack to indicate that a parenthesized expression was replaced. +// pop elements down to and including the open parenthesis off the +// stack. +// push a value onto the stack to indicate that a parenthesized +// expression was replaced. #include using std::stack; @@ -18,29 +20,30 @@ using std::stack; using std::string; #include -using std::cout; using std::endl; +using std::cout; +using std::endl; int main() { - auto & expr = "This is (Mooophy(awesome)((((wooooooooo))))) and (ocxs) over"; - auto repl = '#'; - auto seen = 0; + auto& expr = "This is (Mooophy(awesome)((((wooooooooo))))) and (ocxs) over"; + auto repl = '#'; + auto seen = 0; stack stk; for (auto c : expr) { stk.push(c); - if ( c == '(' ) ++seen; // open - if ( seen && c == ')' ) { // pop elements down to the stack - while ( stk.top() != '(' ) stk.pop(); - stk.pop(); // including the open parenthesis + if (c == '(') ++seen; // open + if (seen && c == ')') { // pop elements down to the stack + while (stk.top() != '(') stk.pop(); + stk.pop(); // including the open parenthesis stk.push(repl); // push a value indicate it was replaced - --seen; // close + --seen; // close } } // Test string output; - for ( ; !stk.empty(); stk.pop() ) output.insert(output.begin(), stk.top()); + for (; !stk.empty(); stk.pop()) output.insert(output.begin(), stk.top()); cout << output << endl; // "This is # and # over" } diff --git a/ch10/ex10_01_02.cpp b/ch10/ex10_01_02.cpp index 3d8de387..6f102c86 100644 --- a/ch10/ex10_01_02.cpp +++ b/ch10/ex10_01_02.cpp @@ -13,27 +13,27 @@ //! Repeat the previous program, but read values into a list of strings. //! - #include #include #include #include #include - int main() { //! 10.1 - std::vector v = { 1, 2, 3, 4, 5, 6, 6, 6, 2 }; - std::cout << "ex 10.01: " << std::count(v.cbegin(), v.cend(), 6) << std::endl; + std::vector v = {1, 2, 3, 4, 5, 6, 6, 6, 2}; + std::cout << "ex 10.01: " << std::count(v.cbegin(), v.cend(), 6) + << std::endl; //! 10.2 - std::list l = { "aa", "aaa", "aa", "cc" }; - std::cout << "ex 10.02: " << std::count(l.cbegin(), l.cend(), "aa") << std::endl; + std::list l = {"aa", "aaa", "aa", "cc"}; + std::cout << "ex 10.02: " << std::count(l.cbegin(), l.cend(), "aa") + << std::endl; return 0; } //! output: //! -//ex 10.01: 3 -//ex 10.02: 2 +// ex 10.01: 3 +// ex 10.02: 2 diff --git a/ch10/ex10_03_04.cpp b/ch10/ex10_03_04.cpp index f70978cc..5db1910f 100644 --- a/ch10/ex10_03_04.cpp +++ b/ch10/ex10_03_04.cpp @@ -17,25 +17,24 @@ #include #include - int main() { //! Exercise 10.3 - std::vector v = {1,2,3,4}; - std::cout << "ex 10.03: " - << std::accumulate(v.cbegin(), v.cend(), 0) + std::vector v = {1, 2, 3, 4}; + std::cout << "ex 10.03: " << std::accumulate(v.cbegin(), v.cend(), 0) << std::endl; //! Exercise 10.4 std::vector vd = {1.1, 0.5, 3.3}; - std::cout << "ex 10.04: " - << std::accumulate(vd.cbegin(), vd.cend(), 0) - << std::endl; //! ^<-- note here. + std::cout << "ex 10.04: " << std::accumulate(vd.cbegin(), vd.cend(), 0) + << std::endl; //! ^<-- note here. //! @attention //! //! The ouput is 4 rather than 4.9 as expected. - //! The reason is std::accumulate is a template function. The third parameter is _Tp __init - //! When "0" , an integer, had been specified here, the compiler deduced _Tp as + //! The reason is std::accumulate is a template function. The third + //! parameter is _Tp __init + //! When "0" , an integer, had been specified here, the compiler deduced _Tp + //! as //! interger.As a result ,when the following statments were being excuted : // for (; __first != __last; ++__first) // __init = __init + *__first; @@ -46,5 +45,5 @@ int main() } //! output //! -//ex 10.03: 10 -//ex 10.04: 4 +// ex 10.03: 10 +// ex 10.04: 4 diff --git a/ch10/ex10_05.cpp b/ch10/ex10_05.cpp index 07b13078..9afcfb8c 100644 --- a/ch10/ex10_05.cpp +++ b/ch10/ex10_05.cpp @@ -5,7 +5,8 @@ // Created by pezy on 11/9/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief In the call to equal on rosters, what would happen if both rosters held C-style strings, rather than library strings? +// @Brief In the call to equal on rosters, what would happen if both rosters +// held C-style strings, rather than library strings? // @Answer It's the same as `std::string` #include @@ -15,8 +16,9 @@ int main() { - std::vector roster1{"Mooophy", "pezy", "Queequeg"}; - std::list roster2{"Mooophy", "pezy", "Queequeg", "shbling", "evan617"}; + std::vector roster1{"Mooophy", "pezy", "Queequeg"}; + std::list roster2{"Mooophy", "pezy", "Queequeg", "shbling", + "evan617"}; std::cout << std::equal(roster1.cbegin(), roster1.cend(), roster2.cbegin()); } diff --git a/ch10/ex10_06.cpp b/ch10/ex10_06.cpp index 4118820d..96552b0b 100644 --- a/ch10/ex10_06.cpp +++ b/ch10/ex10_06.cpp @@ -11,15 +11,17 @@ #include #include -using std::vector; using std::cout; using std::endl; using std::fill_n; +using std::vector; +using std::cout; +using std::endl; +using std::fill_n; int main() { - vector vec{0,1,2,3,4,5,6,7,8,9}; + vector vec{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; fill_n(vec.begin(), vec.size(), 0); - - for (auto i : vec) - cout << i << " "; + + for (auto i : vec) cout << i << " "; cout << endl; } diff --git a/ch10/ex10_07.cpp b/ch10/ex10_07.cpp index 57403d3d..c4196d83 100644 --- a/ch10/ex10_07.cpp +++ b/ch10/ex10_07.cpp @@ -5,20 +5,24 @@ // Created by pezy on 12/9/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief Determine if there are any errors in the following programs and, if so, correct the error(s) +// @Brief Determine if there are any errors in the following programs and, if +// so, correct the error(s) #include #include #include #include -using std::vector; using std::cout; using std::endl; using std::list; using std::cin; using std::fill_n; +using std::vector; +using std::cout; +using std::endl; +using std::list; +using std::cin; +using std::fill_n; -template -void print(Sequence const& seq) +template void print(Sequence const& seq) { - for (const auto& i : seq) - cout << i << " "; + for (const auto& i : seq) cout << i << " "; cout << endl; } @@ -28,17 +32,17 @@ int main() vector vec; list lst; int i; - while (cin >> i) - lst.push_back(i); + while (cin >> i) lst.push_back(i); vec.resize(lst.size()); // ^ Fixed: added this statement // Cause Algorithms that write to a destination iterator assume - // the destination is large enough to hold the number of elements being written. + // the destination is large enough to hold the number of elements being + // written. copy(lst.cbegin(), lst.cend(), vec.begin()); - - //another way to fix bug - //copy(lst.cbegin(), lst.cend(), back_inserter(vec)); - + + // another way to fix bug + // copy(lst.cbegin(), lst.cend(), back_inserter(vec)); + // (b) vector v; v.reserve(10); @@ -46,7 +50,7 @@ int main() // ^ (b)No error, but not any sense. v.size() still equal zero. // Fixed: 1. use `v.resize(10);` // or 2. use `fill_n(std::back_inserter(v), 10, 0)` - + print(v); print(vec); } diff --git a/ch10/ex10_09.cpp b/ch10/ex10_09.cpp index be2ba30b..358a2a1e 100644 --- a/ch10/ex10_09.cpp +++ b/ch10/ex10_09.cpp @@ -14,15 +14,14 @@ #include // print containers like vector,deque, list, etc. -template -auto println(Sequence const& seq) -> std::ostream& +template auto println(Sequence const& seq) -> std::ostream & { - for (auto const& elem : seq) - std::cout << elem << " "; + for (auto const& elem : seq) std::cout << elem << " "; return std::cout << std::endl; } -auto eliminate_duplicates(std::vector &vs) -> std::vector& +auto eliminate_duplicates(std::vector& vs) + -> std::vector & { std::sort(vs.begin(), vs.end()); println(vs); @@ -36,7 +35,7 @@ auto eliminate_duplicates(std::vector &vs) -> std::vector vs{ "a", "v", "a", "s", "v", "a", "a" }; + std::vector vs{"a", "v", "a", "s", "v", "a", "a"}; println(vs); println(eliminate_duplicates(vs)); diff --git a/ch10/ex10_11.cpp b/ch10/ex10_11.cpp index bb0b1f40..1fb9e9d1 100644 --- a/ch10/ex10_11.cpp +++ b/ch10/ex10_11.cpp @@ -13,36 +13,29 @@ #include //! print a container like vector,deque, list,etc. -template -inline std::ostream& println(Sequence const& seq) +template inline std::ostream& println(Sequence const& seq) { - for(auto const& elem : seq) std::cout << elem << " "; + for (auto const& elem : seq) std::cout << elem << " "; std::cout << std::endl; return std::cout; } - -inline bool -is_shorter(std::string const& lhs, std::string const& rhs) +inline bool is_shorter(std::string const& lhs, std::string const& rhs) { - return lhs.size() < rhs.size(); + return lhs.size() < rhs.size(); } - -void elimdups(std::vector &vs) +void elimdups(std::vector& vs) { std::sort(vs.begin(), vs.end()); - auto new_end = std::unique(vs.begin(),vs.end()); + auto new_end = std::unique(vs.begin(), vs.end()); vs.erase(new_end, vs.end()); } - int main() { - std::vector v{ - "1234", "1234", "1234", "Hi", "alan", "wang" - }; + std::vector v{"1234", "1234", "1234", "Hi", "alan", "wang"}; elimdups(v); std::stable_sort(v.begin(), v.end(), is_shorter); std::cout << "ex10.11 :\n"; @@ -51,6 +44,5 @@ int main() return 0; } //! output -//ex10.11 : -//Hi 1234 alan - +// ex10.11 : +// Hi 1234 alan diff --git a/ch10/ex10_12.cpp b/ch10/ex10_12.cpp index 0695a00a..a06416a1 100644 --- a/ch10/ex10_12.cpp +++ b/ch10/ex10_12.cpp @@ -1,6 +1,7 @@ //! @Yue Wang //! Exercise 10.12: -//! Write a function named compareIsbn that compares the isbn() members of two Sales_data objects. +//! Write a function named compareIsbn that compares the isbn() members of two +//! Sales_data objects. //! Use that function to sort a vector that holds Sales_data objects. //! @@ -9,9 +10,9 @@ #include #include #include -#include "../ch07/ex7_26.h" // Sales_data class. +#include "../ch07/ex7_26.h" // Sales_data class. -inline bool compareIsbn(const Sales_data &sd1, const Sales_data &sd2) +inline bool compareIsbn(const Sales_data& sd1, const Sales_data& sd2) { return sd1.isbn().size() < sd2.isbn().size(); } @@ -25,8 +26,7 @@ int main() //! must match the parameters of the predicate. std::sort(v.begin(), v.end(), compareIsbn); - for(const auto &element : v) - std::cout << element.isbn() << " "; + for (const auto& element : v) std::cout << element.isbn() << " "; std::cout << std::endl; return 0; diff --git a/ch10/ex10_13.cpp b/ch10/ex10_13.cpp index 062d5b59..7d79f996 100644 --- a/ch10/ex10_13.cpp +++ b/ch10/ex10_13.cpp @@ -16,18 +16,18 @@ #include #include -bool predicate(const std::string &s) -{ - return s.size() >= 5; +bool predicate(const std::string& s) +{ + return s.size() >= 5; } int main() { - auto v = std::vector{ "a", "as", "aasss", "aaaaassaa", "aaaaaabba", "aaa" }; + auto v = std::vector{"a", "as", "aasss", + "aaaaassaa", "aaaaaabba", "aaa"}; auto pivot = std::partition(v.begin(), v.end(), predicate); - - for (auto it = v.cbegin(); it != pivot; ++it) - std::cout << *it << " "; + + for (auto it = v.cbegin(); it != pivot; ++it) std::cout << *it << " "; std::cout << std::endl; return 0; diff --git a/ch10/ex10_16.cpp b/ch10/ex10_16.cpp index 224d6b68..16f15921 100644 --- a/ch10/ex10_16.cpp +++ b/ch10/ex10_16.cpp @@ -12,48 +12,44 @@ #include //! from ex 10.9 -void elimdups(std::vector &vs) +void elimdups(std::vector& vs) { std::sort(vs.begin(), vs.end()); - auto new_end = std::unique(vs.begin(),vs.end()); + auto new_end = std::unique(vs.begin(), vs.end()); vs.erase(new_end, vs.end()); } -void biggies(std::vector &vs, std::size_t sz) +void biggies(std::vector& vs, std::size_t sz) { using std::string; elimdups(vs); //! sort by size, but maintain alphabetical order for same size. - std::stable_sort(vs.begin(), vs.end(),[](string const& lhs, string const& rhs){ - return lhs.size() < rhs.size(); - }); + std::stable_sort(vs.begin(), vs.end(), + [](string const& lhs, string const& rhs) { + return lhs.size() < rhs.size(); + }); //! get an iterator to the first one whose size() is >= sz - auto wc = std::find_if(vs.begin(), vs.end(),[sz](string const& s){ - return s.size() >= sz; - }); - + auto wc = std::find_if(vs.begin(), vs.end(), + [sz](string const& s) { return s.size() >= sz; }); + //! print the biggies - std::for_each(wc, vs.end(), [](const string &s){ - std::cout << s << " "; - }); + std::for_each(wc, vs.end(), [](const string& s) { std::cout << s << " "; }); } int main() { //! ex10.16 - std::vector v - { - "1234","1234","1234","hi~", "alan", "alan", "cp" - }; + std::vector v{"1234", "1234", "1234", "hi~", + "alan", "alan", "cp"}; std::cout << "ex10.16: "; - biggies(v,3); + biggies(v, 3); std::cout << std::endl; return 0; } //! output : //! -//ex10.16: 1234 alan +// ex10.16: 1234 alan diff --git a/ch10/ex10_17.cpp b/ch10/ex10_17.cpp index 696453f0..7fcdf556 100644 --- a/ch10/ex10_17.cpp +++ b/ch10/ex10_17.cpp @@ -1,8 +1,8 @@ //! @pezy //! //! Exercise 10.17 -//! Rewrite exercise 10.12 from ¡ì 10.3.1 (p. 387) -//! to use a lambda in the call to sort instead of the compareIsbn function. +//! Rewrite exercise 10.12 from ¡ì 10.3.1 (p. 387) +//! to use a lambda in the call to sort instead of the compareIsbn function. //! //! @See 7.26, 10.12 @@ -10,19 +10,19 @@ #include #include #include -#include "../ch07/ex7_26.h" // Sales_data class. +#include "../ch07/ex7_26.h" // Sales_data class. int main() { Sales_data d1("aa"), d2("aaaa"), d3("aaa"), d4("z"), d5("aaaaz"); std::vector v{d1, d2, d3, d4, d5}; - std::sort(v.begin(), v.end(), [](const Sales_data &sd1, const Sales_data &sd2){ - return sd1.isbn().size() < sd2.isbn().size(); - }); + std::sort(v.begin(), v.end(), + [](const Sales_data& sd1, const Sales_data& sd2) { + return sd1.isbn().size() < sd2.isbn().size(); + }); - for(const auto &element : v) - std::cout << element.isbn() << " "; + for (const auto& element : v) std::cout << element.isbn() << " "; std::cout << std::endl; return 0; diff --git a/ch10/ex10_18_19.cpp b/ch10/ex10_18_19.cpp index 4417ac9a..39d294a4 100644 --- a/ch10/ex10_18_19.cpp +++ b/ch10/ex10_18_19.cpp @@ -11,70 +11,63 @@ //! sequence. //! - #include #include #include #include //! from ex 10.9 -void elimdups(std::vector &vs) +void elimdups(std::vector& vs) { std::sort(vs.begin(), vs.end()); - auto new_end = std::unique(vs.begin(),vs.end()); + auto new_end = std::unique(vs.begin(), vs.end()); vs.erase(new_end, vs.end()); } - //! ex10.18 -void biggies_partition(std::vector &vs, std::size_t sz) +void biggies_partition(std::vector& vs, std::size_t sz) { elimdups(vs); - - auto pivot = partition(vs.begin(), vs.end(),[sz](const std::string &s){ - return s.size() >= sz;} - ); - for(auto it = vs.cbegin(); it != pivot; ++it) - std::cout << *it << " "; -} + auto pivot = partition(vs.begin(), vs.end(), [sz](const std::string& s) { + return s.size() >= sz; + }); + for (auto it = vs.cbegin(); it != pivot; ++it) std::cout << *it << " "; +} //! ex10.19 -void biggies_stable_partition(std::vector &vs, std::size_t sz) +void biggies_stable_partition(std::vector& vs, std::size_t sz) { elimdups(vs); - - auto pivot = stable_partition(vs.begin(), vs.end(),[sz](const std::string& s){ - return s.size() >= sz; - }); - for(auto it = vs.cbegin(); it != pivot; ++it) - std::cout << *it << " "; -} + auto pivot = + stable_partition(vs.begin(), vs.end(), + [sz](const std::string& s) { return s.size() >= sz; }); + for (auto it = vs.cbegin(); it != pivot; ++it) std::cout << *it << " "; +} int main() { //! ex10.18 - std::vector v{ - "the", "quick", "red", "fox", "jumps", "over", "the", "slow", "red", "turtle" - }; - + std::vector v{"the", "quick", "red", "fox", "jumps", + "over", "the", "slow", "red", "turtle"}; + std::cout << "ex10.18: "; std::vector v1(v); - biggies_partition(v1,4); + biggies_partition(v1, 4); std::cout << std::endl; //! ex10.19 std::cout << "ex10.19: "; std::vector v2(v); - biggies_stable_partition(v2,4); + biggies_stable_partition(v2, 4); std::cout << std::endl; return 0; } //! output : //! -//ex10.18: turtle jumps over quick slow -//ex10.19: jumps over quick slow turtle +// ex10.18: turtle jumps over quick slow +// ex10.19: jumps over quick slow turtle diff --git a/ch10/ex10_20_21.cpp b/ch10/ex10_20_21.cpp index 0445a7b2..287abc8b 100644 --- a/ch10/ex10_20_21.cpp +++ b/ch10/ex10_20_21.cpp @@ -3,16 +3,23 @@ //! @date 02.12.2014 //! //! Exercise 10.20: -//! The library defines an algorithm named count_if. Like find_if, this function takes -//! a pair of iterators denoting an input range and a predicate that it applies to each -//! element in the given range. count_if returns a count of how often the predicate is -//! true. Use count_if to rewrite the portion of our program that counted how many words +//! The library defines an algorithm named count_if. Like find_if, this function +//! takes +//! a pair of iterators denoting an input range and a predicate that it applies +//! to each +//! element in the given range. count_if returns a count of how often the +//! predicate is +//! true. Use count_if to rewrite the portion of our program that counted how +//! many words //! are greater than length 6. //! //! Exercise 10.21: -//! Write a lambda that captures a local int variable and decrements that variable until -//! it reaches 0. Once the variable is 0 additional calls should no longer decrement the -//! variable. The lambda should return a bool that indicates whether the captured variable is 0. +//! Write a lambda that captures a local int variable and decrements that +//! variable until +//! it reaches 0. Once the variable is 0 additional calls should no longer +//! decrement the +//! variable. The lambda should return a bool that indicates whether the +//! captured variable is 0. //! #include @@ -20,42 +27,35 @@ #include #include - using std::vector; using std::count_if; using std::string; - //! Exercise 10.20 std::size_t bigerThan6(vector const& v) { - return count_if(v.cbegin(), v.cend(), [](string const& s){ - return s.size() > 6; - }); + return count_if(v.cbegin(), v.cend(), + [](string const& s) { return s.size() > 6; }); } - int main() { //! ex10.20 - vector v{ - "alan","moophy","1234567","1234567","1234567","1234567" - }; + vector v{"alan", "moophy", "1234567", + "1234567", "1234567", "1234567"}; std::cout << "ex10.20: " << bigerThan6(v) << std::endl; //! ex10.21 int i = 7; - auto check_and_decrement = [&i](){ return --i ? false : true; }; + auto check_and_decrement = [&i]() { return --i ? false : true; }; std::cout << "ex10.21: "; - while(!check_and_decrement()) - std::cout << i << " "; + while (!check_and_decrement()) std::cout << i << " "; std::cout << i << std::endl; return 0; } - //! output : //! -//ex10.20: 4 -//ex10.21: 6 5 4 3 2 1 0 +// ex10.20: 4 +// ex10.21: 6 5 4 3 2 1 0 diff --git a/ch10/ex10_22.cpp b/ch10/ex10_22.cpp index a4de09ef..6be03679 100644 --- a/ch10/ex10_22.cpp +++ b/ch10/ex10_22.cpp @@ -17,15 +17,17 @@ using std::string; using namespace std::placeholders; -bool isBiggerThan6(const string &s, string::size_type sz) +bool isBiggerThan6(const string& s, string::size_type sz) { return s.size() > sz; } int main() { - std::vector authors{"Mooophy", "pezy", "Queequeg90", "shbling", "evan617"}; - std::cout << count_if(authors.cbegin(), authors.cend(), bind(isBiggerThan6, _1, 6)); + std::vector authors{"Mooophy", "pezy", "Queequeg90", "shbling", + "evan617"}; + std::cout << count_if(authors.cbegin(), authors.cend(), + bind(isBiggerThan6, _1, 6)); } // @Out diff --git a/ch10/ex10_24.cpp b/ch10/ex10_24.cpp index a07fd5f3..a3f7a265 100644 --- a/ch10/ex10_24.cpp +++ b/ch10/ex10_24.cpp @@ -2,7 +2,8 @@ //! @author @Yue Wang @shbling //! //! Exercise 10.24: -//! Use bind and check_size to find the first element in a vector of ints that has a value greater +//! Use bind and check_size to find the first element in a vector of ints that +//! has a value greater //! than the length of a specified string value. //! // Discussion over this exercise on StackOverflow @@ -22,26 +23,26 @@ using std::vector; using std::find_if; using std::bind; -inline bool -check_size(const string &s, string::size_type sz) +inline bool check_size(const string& s, string::size_type sz) { return s.size() < sz; } -inline vector::const_iterator -find_first_bigger(const vector &v, const string &s) +inline vector::const_iterator find_first_bigger(const vector& v, + const string& s) { - return find_if(v.cbegin(), v.cend(), bind(check_size, s, std::placeholders::_1)); + return find_if(v.cbegin(), v.cend(), + bind(check_size, s, std::placeholders::_1)); } int main() { - vector v{1,2,3,4,5,6,7}; + vector v{1, 2, 3, 4, 5, 6, 7}; string s("test"); - cout << *find_first_bigger(v,s) << endl; + cout << *find_first_bigger(v, s) << endl; return 0; } //! output; //! -//5 +// 5 diff --git a/ch10/ex10_25.cpp b/ch10/ex10_25.cpp index b199310e..025e5977 100644 --- a/ch10/ex10_25.cpp +++ b/ch10/ex10_25.cpp @@ -5,7 +5,8 @@ // Created by pezy on 12/11/14. // Copyright (c) 2014 pezy. All rights reserved. // -// @Brief In the exercises for 10.3.2 (p.392) you wrote a version of biggies that uses partition. +// @Brief In the exercises for 10.3.2 (p.392) you wrote a version of biggies +// that uses partition. // Rewrite that function to use check_size and bind. #include @@ -14,32 +15,34 @@ #include #include -using std::string; using std::vector; +using std::string; +using std::vector; using namespace std::placeholders; -void elimdups(vector &vs) +void elimdups(vector& vs) { std::sort(vs.begin(), vs.end()); - vs.erase(unique(vs.begin(),vs.end()), vs.end()); + vs.erase(unique(vs.begin(), vs.end()), vs.end()); } -bool check_size(const string &s, string::size_type sz) +bool check_size(const string& s, string::size_type sz) { return s.size() >= sz; } -void biggies(vector &words, vector::size_type sz) +void biggies(vector& words, vector::size_type sz) { elimdups(words); - auto iter = std::stable_partition(words.begin(), words.end(), bind(check_size, _1, sz)); - for_each(words.begin(), iter, [](const string &s){ std::cout << s << " "; }); + auto iter = std::stable_partition(words.begin(), words.end(), + bind(check_size, _1, sz)); + for_each(words.begin(), iter, + [](const string& s) { std::cout << s << " "; }); } int main() { - std::vector v{ - "the", "quick", "red", "fox", "jumps", "over", "the", "slow", "red", "turtle" - }; + std::vector v{"the", "quick", "red", "fox", "jumps", + "over", "the", "slow", "red", "turtle"}; biggies(v, 4); } diff --git a/ch10/ex10_27.cpp b/ch10/ex10_27.cpp index 48e2d8ab..46e02f09 100644 --- a/ch10/ex10_27.cpp +++ b/ch10/ex10_27.cpp @@ -6,7 +6,8 @@ // Copyright (c) 2014 pezy. All rights reserved. // // In addition to unique, the library defines function named unique_copy that -// takes a third iterator denoting a destination into which to copy the unique elements. +// takes a third iterator denoting a destination into which to copy the unique +// elements. // Write a program that uses unique_copy to copy the unique elements from // a vector into an initially empty list. @@ -17,11 +18,10 @@ int main() { - std::vector vec{1,1,3,3,5,5,7,7,9}; + std::vector vec{1, 1, 3, 3, 5, 5, 7, 7, 9}; std::list lst; - + std::unique_copy(vec.begin(), vec.end(), back_inserter(lst)); - for (auto i : lst) - std::cout << i << " "; + for (auto i : lst) std::cout << i << " "; std::cout << std::endl; } diff --git a/ch10/ex10_28.cpp b/ch10/ex10_28.cpp index 35de5288..8de536a3 100644 --- a/ch10/ex10_28.cpp +++ b/ch10/ex10_28.cpp @@ -5,41 +5,44 @@ // Created by pezy on 12/13/14. // Copyright (c) 2014 pezy. All rights reserved. // -// Copy a vector that holds the values from 1 to 9 inclusive, into three other containers. -// Use an inserter, a back_inserter, and a front_inserter, respectivly to add elements to these containers. -// Predict how the output sequence varies by the kind of inserter and verify your predictions +// Copy a vector that holds the values from 1 to 9 inclusive, into three other +// containers. +// Use an inserter, a back_inserter, and a front_inserter, respectivly to add +// elements to these containers. +// Predict how the output sequence varies by the kind of inserter and verify +// your predictions // by running your programs. - #include #include #include #include -using std::list; using std::copy; using std::cout; using std::endl; +using std::list; +using std::copy; +using std::cout; +using std::endl; -template -void print(Sequence const& seq) +template void print(Sequence const& seq) { - for (const auto& i : seq) - std::cout << i << " "; + for (const auto& i : seq) std::cout << i << " "; std::cout << std::endl; } int main() { - std::vector vec{1,2,3,4,5,6,7,8,9}; - + std::vector vec{1, 2, 3, 4, 5, 6, 7, 8, 9}; + // uses inserter list lst1; copy(vec.cbegin(), vec.cend(), inserter(lst1, lst1.begin())); print(lst1); - + // uses back_inserter list lit2; copy(vec.cbegin(), vec.cend(), back_inserter(lit2)); print(lit2); - + // uses front_inserter list lst3; copy(vec.cbegin(), vec.cend(), front_inserter(lst3)); diff --git a/ch10/ex10_29.cpp b/ch10/ex10_29.cpp index efae7b2f..ce952cc2 100644 --- a/ch10/ex10_29.cpp +++ b/ch10/ex10_29.cpp @@ -5,8 +5,8 @@ // Created by pezy on 12/13/14. // Copyright (c) 2014 pezy. All rights reserved. // -// Write a program using stream iterators to read a text file into a vector of strings. - +// Write a program using stream iterators to read a text file into a vector of +// strings. #include #include @@ -22,7 +22,8 @@ int main() std::istream_iterator in(ifs), eof; std::vector vec; std::copy(in, eof, back_inserter(vec)); - + // output - std::copy(vec.cbegin(), vec.cend(), std::ostream_iterator(std::cout, "\n")); + std::copy(vec.cbegin(), vec.cend(), + std::ostream_iterator(std::cout, "\n")); } diff --git a/ch10/ex10_30.cpp b/ch10/ex10_30.cpp index efe9f55e..da361da2 100644 --- a/ch10/ex10_30.cpp +++ b/ch10/ex10_30.cpp @@ -5,10 +5,10 @@ // Created by pezy on 12/13/14. // Copyright (c) 2014 pezy. All rights reserved. // -// Use stream iterators, sort, and copy to read a sequence of integers from the standard input, +// Use stream iterators, sort, and copy to read a sequence of integers from the +// standard input, // sort them, and then write them back to the standard output. - #include #include #include @@ -18,8 +18,8 @@ int main() { std::istream_iterator in_iter(std::cin), eof; std::vector vec; - while (in_iter != eof) - vec.push_back(*in_iter++); + while (in_iter != eof) vec.push_back(*in_iter++); std::sort(vec.begin(), vec.end()); - std::copy(vec.cbegin(), vec.cend(), std::ostream_iterator(std::cout, " ")); + std::copy(vec.cbegin(), vec.cend(), + std::ostream_iterator(std::cout, " ")); } \ No newline at end of file diff --git a/ch10/ex10_31.cpp b/ch10/ex10_31.cpp index 6897204c..6eaf7a36 100644 --- a/ch10/ex10_31.cpp +++ b/ch10/ex10_31.cpp @@ -5,10 +5,10 @@ // Created by pezy on 12/13/14. // Copyright (c) 2014 pezy. All rights reserved. // -// Update the program from the previous exercise so that it prints only the unique elements. +// Update the program from the previous exercise so that it prints only the +// unique elements. // Your program should use unqiue_copy - #include #include #include @@ -18,8 +18,8 @@ int main() { std::istream_iterator in_iter(std::cin), eof; std::vector vec; - while (in_iter != eof) - vec.push_back(*in_iter++); + while (in_iter != eof) vec.push_back(*in_iter++); std::sort(vec.begin(), vec.end()); - std::unique_copy(vec.cbegin(), vec.cend(), std::ostream_iterator(std::cout, " ")); + std::unique_copy(vec.cbegin(), vec.cend(), + std::ostream_iterator(std::cout, " ")); } \ No newline at end of file diff --git a/ch10/ex10_32.cpp b/ch10/ex10_32.cpp index 0f306ed1..0791e069 100644 --- a/ch10/ex10_32.cpp +++ b/ch10/ex10_32.cpp @@ -5,9 +5,11 @@ // Created by pezy on 12/13/14. // Copyright (c) 2014 pezy. All rights reserved. // -// Rewrite the bookstore problem from 1.6 (p. 24) using a vector to hold the transactions +// Rewrite the bookstore problem from 1.6 (p. 24) using a vector to hold the +// transactions // and various algorithms to do the processing. -// Use sort with your compareIsbn function from 10.3.1 (p. 387) to arrange the transactions in order, +// Use sort with your compareIsbn function from 10.3.1 (p. 387) to arrange the +// transactions in order, // and then use find and accumulate to do the sum. #include @@ -21,12 +23,17 @@ int main() { std::istream_iterator in_iter(std::cin), in_eof; std::vector vec; - - while (in_iter != in_eof) - vec.push_back(*in_iter++); - sort(vec.begin(), vec.end(), [](Sales_item const& lhs, Sales_item const& rhs){ return lhs.isbn() < rhs.isbn(); }); + + while (in_iter != in_eof) vec.push_back(*in_iter++); + sort(vec.begin(), vec.end(), + [](Sales_item const& lhs, Sales_item const& rhs) { + return lhs.isbn() < rhs.isbn(); + }); for (auto beg = vec.cbegin(), end = beg; beg != vec.cend(); beg = end) { - end = find_if(beg, vec.cend(), [beg](const Sales_item &item){return item.isbn() != beg->isbn();}); - std::cout << std::accumulate(beg, end, Sales_item(beg->isbn())) << std::endl; + end = find_if(beg, vec.cend(), [beg](const Sales_item& item) { + return item.isbn() != beg->isbn(); + }); + std::cout << std::accumulate(beg, end, Sales_item(beg->isbn())) + << std::endl; } } diff --git a/ch10/ex10_33.cpp b/ch10/ex10_33.cpp index d1db6f23..2293808f 100644 --- a/ch10/ex10_33.cpp +++ b/ch10/ex10_33.cpp @@ -6,9 +6,11 @@ // Copyright (c) 2014 pezy. All rights reserved. // // Write a program that takes the names of an input file and two output files. -// The input file should hold integers. Using an istream_iterator read the input file. +// The input file should hold integers. Using an istream_iterator read the +// input file. // Using ostream_iterators, write the odd numbers into the first output file. -// Each value should be followed by a space.Write the even numbers into the second file. +// Each value should be followed by a space.Write the even numbers into the +// second file. // Each of these values should be placed on a separate line. // // Run: ./a.out "../data/input.txt" "../data/odd.txt" "../data/even.txt" @@ -17,7 +19,7 @@ #include #include -int main(int argc, char **argv) +int main(int argc, char** argv) { if (argc != 4) return -1; @@ -27,8 +29,8 @@ int main(int argc, char **argv) std::istream_iterator in(ifs), in_eof; std::ostream_iterator out_odd(ofs_odd, " "), out_even(ofs_even, "\n"); - std::for_each(in, in_eof, [&out_odd, &out_even](const int i){ - *(i&0x1 ? out_odd : out_even)++ = i; + std::for_each(in, in_eof, [&out_odd, &out_even](const int i) { + *(i & 0x1 ? out_odd : out_even)++ = i; }); return 0; diff --git a/ch10/ex10_34_35_36_37.cpp b/ch10/ex10_34_35_36_37.cpp index 983f152a..2ba93d7c 100644 --- a/ch10/ex10_34_35_36_37.cpp +++ b/ch10/ex10_34_35_36_37.cpp @@ -22,25 +22,21 @@ #include //! Exercise 10.34 -void -r_print(const std::vector &v); +void r_print(const std::vector& v); //! Exercise 10.35 -void -r_withOrdinary_print(const std::vector &v); +void r_withOrdinary_print(const std::vector& v); //! Exercise 10.36 -std::list::iterator -find_last_0(std::list &l); +std::list::iterator find_last_0(std::list& l); //! Exercise 10.37 -void -vec2list_3_7_reverse(const std::vector &v, std::list &l); +void vec2list_3_7_reverse(const std::vector& v, std::list& l); int main() { - std::vector v={"aa","bb","cc"}; + std::vector v = {"aa", "bb", "cc"}; //! test for 10.34 r_print(v); @@ -51,34 +47,29 @@ int main() std::cout << "\n"; //! test for 10.36 - std::list l = {1,2,3,4,0,5,6}; + std::list l = {1, 2, 3, 4, 0, 5, 6}; auto it = find_last_0(l); std::cout << *it << "\n"; //! test for 10.37 - std::vector vi = {1,2,3,4,5,6,7,8,9,10}; - std::list lst; - vec2list_3_7_reverse(vi,lst); - for(auto e : lst) - std::cout << e <<" "; + std::vector vi = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + std::list lst; + vec2list_3_7_reverse(vi, lst); + for (auto e : lst) std::cout << e << " "; std::cout << std::endl; return 0; } //! Exercise 10.34 -inline void -r_print(const std::vector &v) +inline void r_print(const std::vector& v) { - std::for_each(v.crbegin(), v.crend(), [](const std::string &s) - { - std::cout << s << " "; - }); + std::for_each(v.crbegin(), v.crend(), + [](const std::string& s) { std::cout << s << " "; }); } //! Exercise 10.35 -inline void -r_withOrdinary_print(const std::vector &v) +inline void r_withOrdinary_print(const std::vector& v) { for (auto it = std::prev(v.cend()); it != std::prev(v.cbegin()); --it) std::cout << *it << " "; @@ -87,8 +78,7 @@ r_withOrdinary_print(const std::vector &v) //! Exercise 10.36 //! @note reverse iterator can not conver to oridinary directly //! it may be done via the member base(). -inline std::list::iterator -find_last_0(std::list &l) +inline std::list::iterator find_last_0(std::list& l) { //! assumimg : 1 2 3 4 0 5 6 @@ -106,14 +96,12 @@ find_last_0(std::list &l) //! ^ //! to which --it refer. return std::prev(it); - } //! Exercise 10.37: //! Given a vector that has ten elements, copy the elements from positions //! 3 through 7 in reverse order to a list. -inline void -vec2list_3_7_reverse(const std::vector &v, std::list &l) +inline void vec2list_3_7_reverse(const std::vector& v, std::list& l) { //! 1 2 3 4 5 6 7 8 9 10 //! ^ ^^ @@ -124,5 +112,6 @@ vec2list_3_7_reverse(const std::vector &v, std::list &l) //! hence, the arguments here denote: //! [7 6 5 4 3 2) //! ^ this one is specified but not included. - //! @note: also const vecrions if functions can be used. v.crbegin() and v.crbegin() + //! @note: also const vecrions if functions can be used. v.crbegin() and + //! v.crbegin() } diff --git a/ch10/ex10_42.cpp b/ch10/ex10_42.cpp index 527f26b0..9b85ddd9 100644 --- a/ch10/ex10_42.cpp +++ b/ch10/ex10_42.cpp @@ -9,9 +9,10 @@ #include #include -using std::string; using std::list; +using std::string; +using std::list; -void elimDups(list &words) +void elimDups(list& words) { words.sort(); words.unique(); @@ -19,13 +20,12 @@ void elimDups(list &words) int main() { - list l = {"aa","aa","aa","aa","aasss","aa"}; + list l = {"aa", "aa", "aa", "aa", "aasss", "aa"}; elimDups(l); - for(const auto& e : l) - std::cout << e << " "; + for (const auto& e : l) std::cout << e << " "; std::cout << std::endl; } //! output //! -//aa aasss +// aa aasss diff --git a/ch11/ex11_11.cpp b/ch11/ex11_11.cpp index 9d66dc39..ffabddc3 100644 --- a/ch11/ex11_11.cpp +++ b/ch11/ex11_11.cpp @@ -10,14 +10,14 @@ #include "../ch07/ex7_26.h" #include -bool compareIsbn(const Sales_data &lhs, const Sales_data &rhs) +bool compareIsbn(const Sales_data& lhs, const Sales_data& rhs) { return lhs.isbn() < rhs.isbn(); } int main() { - using compareType = bool (*)(const Sales_data &lhs, const Sales_data &rhs); - //typedef bool(*compareType)(const Sales_data &lhs, const Sales_data &rhs); + using compareType = bool (*)(const Sales_data& lhs, const Sales_data& rhs); + // typedef bool(*compareType)(const Sales_data &lhs, const Sales_data &rhs); std::multiset bookstore(compareIsbn); } \ No newline at end of file diff --git a/ch11/ex11_12_13.cpp b/ch11/ex11_12_13.cpp index f8c2bd06..94ab8914 100644 --- a/ch11/ex11_12_13.cpp +++ b/ch11/ex11_12_13.cpp @@ -8,7 +8,8 @@ // Write a program to read a sequence of strings and ints, // storing each into a pair. Store the pairs in a vector. // -// There are at least three ways to create the pairs in the program for the previous exercise. +// There are at least three ways to create the pairs in the program for the +// previous exercise. // Write three versions of that program, creating the pairs in each way. // Explain which form you think is easiest to write and understand, and why. @@ -24,10 +25,10 @@ int main() int i; while (std::cin >> str >> i) vec.push_back(std::pair(str, i)); - //vec.push_back(std::make_pair(str, i)); - //vec.push_back({str, i}); - //vec.emplace_back(str, i); //!!! easiest way. - - for (const auto &p : vec) + // vec.push_back(std::make_pair(str, i)); + // vec.push_back({str, i}); + // vec.emplace_back(str, i); //!!! easiest way. + + for (const auto& p : vec) std::cout << p.first << ":" << p.second << std::endl; } \ No newline at end of file diff --git a/ch11/ex11_14.cpp b/ch11/ex11_14.cpp index 224edf83..3a98c98c 100644 --- a/ch11/ex11_14.cpp +++ b/ch11/ex11_14.cpp @@ -15,15 +15,21 @@ #include #include -using std::ostream; using std::cout; using std::cin; using std::endl; using std::string; -using std::make_pair; using std::pair; using std::vector; using std::map; +using std::ostream; +using std::cout; +using std::cin; +using std::endl; +using std::string; +using std::make_pair; +using std::pair; +using std::vector; +using std::map; -class Families -{ +class Families { public: - using Child = pair; - using Children = vector; - using Data = map; + using Child = pair; + using Children = vector; + using Data = map; void add(string const& last_name, string const& first_name, string birthday) { @@ -32,12 +38,10 @@ class Families ostream& print(std::ostream& os) const { - if (_data.empty()) - return os << "No data right now." << endl; + if (_data.empty()) return os << "No data right now." << endl; - for (const auto& pair : _data) - { - os << pair.first << ":\n" ; + for (const auto& pair : _data) { + os << pair.first << ":\n"; for (const auto& child : pair.second) os << child.first << " " << child.second << endl; os << endl; @@ -53,7 +57,9 @@ int main() { Families families; string message = "Please enter last name, first name and birthday"; - for (string l, f, b; cout << message << endl, cin >> l >> f >> b; families.add(l, f, b)); + for (string l, f, b; cout << message << endl, cin >> l >> f >> b; + families.add(l, f, b)) + ; families.print(cout << "Current data:" << endl); return 0; diff --git a/ch11/ex11_18.cpp b/ch11/ex11_18.cpp index b414c5ce..fdd2d419 100644 --- a/ch11/ex11_18.cpp +++ b/ch11/ex11_18.cpp @@ -1,7 +1,8 @@ //! @Alan //! //! Exercise 11.18: -//! Write the type of map_it from the loop on page 430 without using auto or decltype. +//! Write the type of map_it from the loop on page 430 without using auto or +//! decltype. //! #include @@ -13,20 +14,18 @@ int main() std::map word_count; //! the orignal codes: - //auto map_it = word_count.cbegin(); - + // auto map_it = word_count.cbegin(); std::map::const_iterator map_it = word_count.cbegin(); -//! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! the type ex11.18 required. + //! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + //! the type ex11.18 required. // compare the current iterator to the off-the-end iterator - while (map_it != word_count.cend()) - { + while (map_it != word_count.cend()) { // dereference the iterator to print the element key--value pairs - std::cout << map_it->first << " occurs " - << map_it->second << " times" << std::endl; - ++map_it; // increment the iterator to denote the next element + std::cout << map_it->first << " occurs " << map_it->second << " times" + << std::endl; + ++map_it; // increment the iterator to denote the next element } return 0; diff --git a/ch11/ex11_20.cpp b/ch11/ex11_20.cpp index c888d602..7ace69d3 100644 --- a/ch11/ex11_20.cpp +++ b/ch11/ex11_20.cpp @@ -16,14 +16,13 @@ int main() { std::map word_count; string word; - while(std::cin >> word) - { - auto ret = word_count.insert({word,1}); - if(!ret.second) ++ret.first->second; + while (std::cin >> word) { + auto ret = word_count.insert({word, 1}); + if (!ret.second) ++ret.first->second; } //! print the content of the map. - for(const auto &w : word_count) + for (const auto& w : word_count) std::cout << w.first << " " << w.second - << ((w.second > 1) ? " times" : " time") << std::endl; + << ((w.second > 1) ? " times" : " time") << std::endl; } diff --git a/ch11/ex11_23.cpp b/ch11/ex11_23.cpp index fdde1060..b89b26cf 100644 --- a/ch11/ex11_23.cpp +++ b/ch11/ex11_23.cpp @@ -5,7 +5,8 @@ // Created by pezy on 12/16/14. // Copyright (c) 2014 pezy. All rights reserved. // -// Rewrite the map that stored vectors of children’s names with a key that is the family last name for the exercises in 11.2.1 (p. 424) to use a multimap. +// Rewrite the map that stored vectors of children’s names with a key that is +// the family last name for the exercises in 11.2.1 (p. 424) to use a multimap. #include #include @@ -16,7 +17,9 @@ using std::string; int main() { std::multimap families; - for (string lastName, childName; std::cin >> childName >> lastName; families.emplace(lastName, childName)); - for (const auto &s : families) + for (string lastName, childName; std::cin >> childName >> lastName; + families.emplace(lastName, childName)) + ; + for (const auto& s : families) std::cout << s.second << " " << s.first << std::endl; } \ No newline at end of file diff --git a/ch11/ex11_24_25_26.cpp b/ch11/ex11_24_25_26.cpp index ead09548..bf145df6 100644 --- a/ch11/ex11_24_25_26.cpp +++ b/ch11/ex11_24_25_26.cpp @@ -30,33 +30,27 @@ int main() { //! ex11.24 std::map m; - m[0]=1; - - for(const auto &e : m) - std::cout << e.first << " " << e.second <<"\n"; - + m[0] = 1; + for (const auto& e : m) std::cout << e.first << " " << e.second << "\n"; //! ex11.25 std::vector v; - v[0]=1; - - for (const auto &e : v) - std::cout << e << "\n"; - + v[0] = 1; + for (const auto& e : v) std::cout << e << "\n"; //! ex11.26 - std::map map = {{1,"ss"},{2,"sz"}}; + std::map map = {{1, "ss"}, {2, "sz"}}; std::map::key_type type_to_subscript = 1; -//! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! that is, int. - - std::map::mapped_type type_to_return = map[type_to_subscript]; -//! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! that is, std::string + //! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + //! that is, int. + std::map::mapped_type type_to_return = + map[type_to_subscript]; + //! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + //! that is, std::string return 0; } diff --git a/ch11/ex11_27_28_29_30.cpp b/ch11/ex11_27_28_29_30.cpp index cd9c4e69..59a652ab 100644 --- a/ch11/ex11_27_28_29_30.cpp +++ b/ch11/ex11_27_28_29_30.cpp @@ -4,7 +4,8 @@ //! What kinds of problems would you use count to solve? //! When might you use find instead? // I would use count to deal with multimap or multi multiset. -// As for the associative container that have unique key, I would use find instead of count. +// As for the associative container that have unique key, I would use find +// instead of count. //! //! Exercise 11.28: //! Define and initialize a variable to hold the result of @@ -28,8 +29,10 @@ //! cout << pos.first->second << endl; // ^^^^^^^^^^^^^^^^^ // pos a pair -// pos.first the iterator refering to the first element with the matching key -// pos.first->second the value part of the key-value of the first element with the matching key +// pos.first the iterator refering to the first element with the +// matching key +// pos.first->second the value part of the key-value of the first element +// with the matching key #include #include @@ -40,12 +43,16 @@ int main() { std::map> m; - m = {{"Alan",{1,2,3,4,5,}},{"John",{1,5,6,7,8}}}; + m = {{"Alan", + { + 1, 2, 3, 4, 5, + }}, + {"John", {1, 5, 6, 7, 8}}}; //! ex11.28 std::map>::iterator it; -//! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! type used to define this iterator. + //! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + //! type used to define this iterator. it = m.find("Alan"); diff --git a/ch11/ex11_31.cpp b/ch11/ex11_31.cpp index bfbdd226..4dd2cd54 100644 --- a/ch11/ex11_31.cpp +++ b/ch11/ex11_31.cpp @@ -7,7 +7,8 @@ // // Write a program that defines a multimap of authors and their works. // Use **find** to find **an element** in the multimap and erase that element. -// Be sure your program works correctly if the element you look for is not in the map. +// Be sure your program works correctly if the element you look for is not in +// the map. #include #include @@ -18,28 +19,23 @@ using std::string; int main() { std::multimap authors{ - {"alan", "DMA"}, - {"pezy", "LeetCode"}, - {"alan", "CLRS"}, - {"wang", "FTP"}, - {"pezy", "CP5"}, - {"wang", "CPP-Concurrency"} - }; + {"alan", "DMA"}, {"pezy", "LeetCode"}, {"alan", "CLRS"}, + {"wang", "FTP"}, {"pezy", "CP5"}, {"wang", "CPP-Concurrency"}}; // want to delete an element that author is [Alan], work is [112]. string author = "pezy"; string work = "CP5"; - + auto found = authors.find(author); auto count = authors.count(author); while (count) { if (found->second == work) { authors.erase(found); - break; + break; } ++found; --count; } - - for (const auto &author : authors) + + for (const auto& author : authors) std::cout << author.first << " " << author.second << std::endl; } diff --git a/ch11/ex11_32.cpp b/ch11/ex11_32.cpp index 7f807b00..ba54dffd 100644 --- a/ch11/ex11_32.cpp +++ b/ch11/ex11_32.cpp @@ -5,7 +5,8 @@ // Created by pezy on 12/17/14. // Copyright (c) 2014 pezy. All rights reserved. // -// Using the multimap from the previous exercise, write a program to print the list of **authors and their works** alphabetically. +// Using the multimap from the previous exercise, write a program to print the +// list of **authors and their works** alphabetically. #include #include @@ -17,20 +18,14 @@ using std::string; int main() { std::multimap authors{ - {"alan", "DMA"}, - {"pezy", "LeetCode"}, - {"alan", "CLRS"}, - {"wang", "FTP"}, - {"pezy", "CP5"}, - {"wang", "CPP-Concurrency"} - }; + {"alan", "DMA"}, {"pezy", "LeetCode"}, {"alan", "CLRS"}, + {"wang", "FTP"}, {"pezy", "CP5"}, {"wang", "CPP-Concurrency"}}; std::map> order_authors; - for (const auto &author : authors) + for (const auto& author : authors) order_authors[author.first].insert(author.second); - for (const auto &author : order_authors) { + for (const auto& author : order_authors) { std::cout << author.first << ": "; - for (const auto &work : author.second) - std::cout << work << " "; + for (const auto& work : author.second) std::cout << work << " "; std::cout << std::endl; } } diff --git a/ch11/ex11_33.cpp b/ch11/ex11_33.cpp index 27bc0c65..c4ee0007 100644 --- a/ch11/ex11_33.cpp +++ b/ch11/ex11_33.cpp @@ -9,32 +9,35 @@ #include #include -#include +#include #include #include -using std::string; using std::ifstream; +using std::string; +using std::ifstream; -std::map buildMap(ifstream &map_file) +std::map buildMap(ifstream& map_file) { std::map trans_map; - for (string key, value; map_file >> key && getline(map_file, value); ) - if (value.size() > 1) trans_map[key] = value.substr(1).substr(0, value.find_last_not_of(' ')); + for (string key, value; map_file >> key && getline(map_file, value);) + if (value.size() > 1) + trans_map[key] = + value.substr(1).substr(0, value.find_last_not_of(' ')); return trans_map; } -const string & transform(const string &s, const std::map &m) +const string& transform(const string& s, const std::map& m) { auto map_it = m.find(s); return map_it == m.cend() ? s : map_it->second; } -void word_transform(ifstream &map, ifstream &input) +void word_transform(ifstream& map, ifstream& input) { auto trans_map = buildMap(map); - for (string text; getline(input, text); ) { + for (string text; getline(input, text);) { std::istringstream iss(text); - for (string word; iss >> word; ) + for (string word; iss >> word;) std::cout << transform(word, trans_map) << " "; std::cout << std::endl; } @@ -42,7 +45,10 @@ void word_transform(ifstream &map, ifstream &input) int main() { - ifstream ifs_map("../data/word_transformation_bad.txt"), ifs_content("../data/given_to_transform.txt"); - if (ifs_map && ifs_content) word_transform(ifs_map, ifs_content); - else std::cerr << "can't find the documents." << std::endl; + ifstream ifs_map("../data/word_transformation_bad.txt"), + ifs_content("../data/given_to_transform.txt"); + if (ifs_map && ifs_content) + word_transform(ifs_map, ifs_content); + else + std::cerr << "can't find the documents." << std::endl; } diff --git a/ch11/ex11_38.cpp b/ch11/ex11_38.cpp index d84146ac..09211334 100644 --- a/ch11/ex11_38.cpp +++ b/ch11/ex11_38.cpp @@ -5,7 +5,8 @@ // Created by pezy on 12/18/14. // Copyright (c) 2014 pezy. All rights reserved. // -// Rewrite the word-counting (11.1, p. 421) and word-transformation (11.3.6, p. 440) programs to use an unordered_map. +// Rewrite the word-counting (11.1, p. 421) and word-transformation (11.3.6, p. +// 440) programs to use an unordered_map. #include #include @@ -19,32 +20,38 @@ using std::string; void wordCounting() { std::unordered_map word_count; - for (string word; std::cin >> word; ++word_count[word]); - for (const auto &w : word_count) - std::cout << w.first << " occurs " << w.second << (w.second > 1 ? "times" : "time") << std::endl; + for (string word; std::cin >> word; ++word_count[word]) + ; + for (const auto& w : word_count) + std::cout << w.first << " occurs " << w.second + << (w.second > 1 ? "times" : "time") << std::endl; } void wordTransformation() { - std::ifstream ifs_map("../data/word_transformation.txt"), ifs_content("../data/given_to_transform.txt"); + std::ifstream ifs_map("../data/word_transformation.txt"), + ifs_content("../data/given_to_transform.txt"); if (!ifs_map || !ifs_content) { std::cerr << "can't find the documents." << std::endl; return; } - + std::unordered_map trans_map; - for (string key, value; ifs_map >> key && getline(ifs_map, value); ) - if (value.size() > 1) trans_map[key] = value.substr(1).substr(0, value.find_last_not_of(' ')); - + for (string key, value; ifs_map >> key && getline(ifs_map, value);) + if (value.size() > 1) + trans_map[key] = + value.substr(1).substr(0, value.find_last_not_of(' ')); + for (string text, word; getline(ifs_content, text); std::cout << std::endl) - for (std::istringstream iss(text); iss >> word; ) { + for (std::istringstream iss(text); iss >> word;) { auto map_it = trans_map.find(word); - std::cout << (map_it == trans_map.cend() ? word : map_it->second) << " "; + std::cout << (map_it == trans_map.cend() ? word : map_it->second) + << " "; } } int main() { - //wordCounting(); + // wordCounting(); wordTransformation(); } \ No newline at end of file diff --git a/ch11/ex11_3_4.cpp b/ch11/ex11_3_4.cpp index da1f5559..b3e3671b 100644 --- a/ch11/ex11_3_4.cpp +++ b/ch11/ex11_3_4.cpp @@ -16,21 +16,19 @@ #include //! Exercise 11.4 -void word_count_pro(std::map &m) +void word_count_pro(std::map& m) { std::string word; - while(std::cin >> word) - { - for(auto& ch : word) - ch = tolower(ch); + while (std::cin >> word) { + for (auto& ch : word) ch = tolower(ch); //! According to the erase-remove idiom. //! For more information about the erase-remove idiom, please refer to //! http://en.wikipedia.org/wiki/Erase-remove_idiom - word.erase(std::remove_if(word.begin(), word.end(), ispunct), word.end()); + word.erase(std::remove_if(word.begin(), word.end(), ispunct), + word.end()); ++m[word]; } - for (const auto &e : m) - std::cout << e.first << " : " << e.second <<"\n"; + for (const auto& e : m) std::cout << e.first << " : " << e.second << "\n"; } //! Exercise 11.3 @@ -38,11 +36,10 @@ void ex11_3() { std::map word_count; std::string word; - while(std::cin >> word) - ++word_count[word]; + while (std::cin >> word) ++word_count[word]; - for (const auto &elem : word_count) - std::cout << elem.first << " : " << elem.second <<"\n"; + for (const auto& elem : word_count) + std::cout << elem.first << " : " << elem.second << "\n"; } int main() diff --git a/ch11/ex11_7.cpp b/ch11/ex11_7.cpp index 6f298a7b..c5c4c44f 100644 --- a/ch11/ex11_7.cpp +++ b/ch11/ex11_7.cpp @@ -13,8 +13,6 @@ #include #include - - int main() { std::map> famls; @@ -23,37 +21,31 @@ int main() //! while(lambda) //! go to the discussions on stack overfow for more. - while([&]() -> bool - { - std::cout << "Please enter last name:\n"; + while ([&]() -> bool { + std::cout << "Please enter last name:\n"; - return std::cin>>lastName && lastName != "@q"; + return std::cin >> lastName && lastName != "@q"; }()) -//! ^^ -//! the () used here is to call the lambda ,otherwise it does not work -//! go to the post on stack overflow for more detail. + //! ^^ + //! the () used here is to call the lambda ,otherwise it does not work + //! go to the post on stack overflow for more detail. { std::cout << "PLZ Enter children's name:\n"; - while(std::cin >> chldName && chldName != "@q") - { + while (std::cin >> chldName && chldName != "@q") { //! add new items into the vector famls[lastName].push_back(chldName); } } //! iterate through the map. - for(auto e : famls) - { + for (auto e : famls) { std::cout << e.first << ":\n"; //! iterate through the vector. - for(auto c : e.second) - std::cout << c << " "; + for (auto c : e.second) std::cout << c << " "; std::cout << "\n"; } return 0; } - - diff --git a/ch11/ex11_8.cpp b/ch11/ex11_8.cpp index b24aff9e..0c45da70 100644 --- a/ch11/ex11_8.cpp +++ b/ch11/ex11_8.cpp @@ -29,12 +29,13 @@ int main() { - std::vector exclude = {"aa","bb","cc"}; - for (std::string word; std::cin >> word; ) { - if (std::find(exclude.begin(), exclude.end(), word) != exclude.end()) std::cout << "excluded!" << std::endl; - else exclude.push_back(word); + std::vector exclude = {"aa", "bb", "cc"}; + for (std::string word; std::cin >> word;) { + if (std::find(exclude.begin(), exclude.end(), word) != exclude.end()) + std::cout << "excluded!" << std::endl; + else + exclude.push_back(word); } - for (auto const& s : exclude) - std::cout << s << " "; + for (auto const& s : exclude) std::cout << s << " "; std::cout << std::endl; } diff --git a/ch11/ex11_9_10.cpp b/ch11/ex11_9_10.cpp index 8b5673e2..1720a88c 100644 --- a/ch11/ex11_9_10.cpp +++ b/ch11/ex11_9_10.cpp @@ -26,16 +26,13 @@ int main() std::map::iterator, int> mv; std::map::iterator, int> ml; - std::vector vi; - mv.insert(std::pair::iterator, int>(vi.begin(),0)); + mv.insert(std::pair::iterator, int>(vi.begin(), 0)); //! but when using this one the compiler complained that //! error: no match for 'operator<' in '__x < __y' std::list li; - ml.insert(std::pair::iterator,int>(li.begin(),0)); + ml.insert(std::pair::iterator, int>(li.begin(), 0)); return 0; } - - diff --git a/ch12/ex12_02.h b/ch12/ex12_02.h index aa96dfcf..7da0593e 100644 --- a/ch12/ex12_02.h +++ b/ch12/ex12_02.h @@ -5,7 +5,8 @@ // Created by pezy on 12/22/14. // Copyright (c) 2014 pezy. All rights reserved. // -// Write your own version of the StrBlob class including the const versions of front and back. +// Write your own version of the StrBlob class including the const versions of +// front and back. #include #include @@ -13,45 +14,55 @@ #include #include -using std::vector; using std::string; +using std::vector; +using std::string; class StrBlob { public: using size_type = vector::size_type; - StrBlob():data(std::make_shared>()) { } - StrBlob(std::initializer_list il):data(std::make_shared>(il)) { } + StrBlob() : data(std::make_shared>()) {} + StrBlob(std::initializer_list il) + : data(std::make_shared>(il)) + { + } size_type size() const { return data->size(); } bool empty() const { return data->empty(); } - void push_back(const string &t) { data->push_back(t); } - void pop_back() { + void push_back(const string& t) { data->push_back(t); } + void pop_back() + { check(0, "pop_back on empty StrBlob"); data->pop_back(); } - std::string& front() { + std::string& front() + { check(0, "front on empty StrBlob"); return data->front(); } - std::string& back() { + std::string& back() + { check(0, "back on empty StrBlob"); return data->back(); } - const std::string& front() const { + const std::string& front() const + { check(0, "front on empty StrBlob"); return data->front(); } - const std::string& back() const { + const std::string& back() const + { check(0, "back on empty StrBlob"); return data->back(); } private: - void check(size_type i, const string &msg) const { + void check(size_type i, const string& msg) const + { if (i >= data->size()) throw std::out_of_range(msg); } diff --git a/ch12/ex12_06.cpp b/ch12/ex12_06.cpp index 9b06672c..e7185500 100644 --- a/ch12/ex12_06.cpp +++ b/ch12/ex12_06.cpp @@ -18,14 +18,11 @@ #include #include -std::vector* -dynamic_vector_generator(); +std::vector* dynamic_vector_generator(); -void -dynamic_vector_processor(std::vector* ptr_v); +void dynamic_vector_processor(std::vector* ptr_v); -void -dynamic_vector_printer(std::vector* ptr_v); +void dynamic_vector_printer(std::vector* ptr_v); int main() { @@ -38,15 +35,13 @@ int main() delete ptr_vi; - return 0; } /** * @brief return a pointer to dynamicly allocated vector of ints */ -std::vector * -dynamic_vector_generator() +std::vector* dynamic_vector_generator() { std::vector* ptr_v = new std::vector(); return ptr_v; @@ -56,22 +51,19 @@ dynamic_vector_generator() * @brief return a pointer to vector of ints * @param ptr_v pointer to vector of ints */ -void dynamic_vector_processor(std::vector *ptr_v) +void dynamic_vector_processor(std::vector* ptr_v) { int i; std::cout << "plz enter:\n"; - while(std::cin >>i && i != 999) - ptr_v->push_back(i); - + while (std::cin >> i && i != 999) ptr_v->push_back(i); } /** * @brief print the content of the vector that ptr_v points to * @param ptr_v */ -void dynamic_vector_printer(std::vector *ptr_v) +void dynamic_vector_printer(std::vector* ptr_v) { - for(const auto &e : *ptr_v) - std::cout << e << " "; + for (const auto& e : *ptr_v) std::cout << e << " "; std::cout << "\n"; } diff --git a/ch12/ex12_07.cpp b/ch12/ex12_07.cpp index e7872fff..aac6df11 100644 --- a/ch12/ex12_07.cpp +++ b/ch12/ex12_07.cpp @@ -24,27 +24,21 @@ /** * @brief functions for ex12.6 */ -std::vector* -dynamic_vector_generator(); +std::vector* dynamic_vector_generator(); -void -dynamic_vector_processor(std::vector* ptr_v); +void dynamic_vector_processor(std::vector* ptr_v); -void -dynamic_vector_printer(std::vector* ptr_v); +void dynamic_vector_printer(std::vector* ptr_v); /** * @brief functions for ex12.7 */ -std::shared_ptr> -dynamic_vector_generator_sptr(); +std::shared_ptr> dynamic_vector_generator_sptr(); -void -dynamic_vector_processor_sptr(std::shared_ptr> sptr_vi); - -void -dynamic_vector_printer_sptr(const std::shared_ptr> sptr_vi); +void dynamic_vector_processor_sptr(std::shared_ptr> sptr_vi); +void dynamic_vector_printer_sptr( + const std::shared_ptr> sptr_vi); int main() { @@ -52,7 +46,6 @@ int main() dynamic_vector_processor_sptr(sptr); dynamic_vector_printer_sptr(sptr); - return 0; } @@ -60,8 +53,7 @@ int main() * @brief return a pointer to dynamicly allocated vector of ints * ex12.6 */ -std::vector* -dynamic_vector_generator() +std::vector* dynamic_vector_generator() { std::vector* ptr_v = new std::vector(); return ptr_v; @@ -72,14 +64,11 @@ dynamic_vector_generator() * ex12.6 * @param ptr_v pointer to vector of ints */ -void -dynamic_vector_processor(std::vector *ptr_v) +void dynamic_vector_processor(std::vector* ptr_v) { int i; std::cout << "plz enter:\n"; - while(std::cin >>i && i != 999) - ptr_v->push_back(i); - + while (std::cin >> i && i != 999) ptr_v->push_back(i); } /** @@ -87,20 +76,18 @@ dynamic_vector_processor(std::vector *ptr_v) * ex12.6 * @param ptr_v */ -void dynamic_vector_printer(std::vector *ptr_v) +void dynamic_vector_printer(std::vector* ptr_v) { - for(const auto &e : *ptr_v) - std::cout << e << " "; + for (const auto& e : *ptr_v) std::cout << e << " "; std::cout << "\n"; } /** * @brief return a shared_prt to vector of ints */ -std::shared_ptr> -dynamic_vector_generator_sptr() +std::shared_ptr> dynamic_vector_generator_sptr() { - return std::make_shared >(); + return std::make_shared>(); } /** @@ -108,19 +95,16 @@ dynamic_vector_generator_sptr() * return a shared_ptr pointing to it * @param sptr_vi */ -void -dynamic_vector_processor_sptr(std::shared_ptr> sptr_vi) +void dynamic_vector_processor_sptr(std::shared_ptr> sptr_vi) { int i; std::cout << "plz enter:\n"; - while(std::cin >>i && i != 999) - sptr_vi->push_back(i); + while (std::cin >> i && i != 999) sptr_vi->push_back(i); } -void -dynamic_vector_printer_sptr(const std::shared_ptr > sptr_vi) +void dynamic_vector_printer_sptr( + const std::shared_ptr> sptr_vi) { - for(const auto &e : *sptr_vi) - std::cout << e << " "; + for (const auto& e : *sptr_vi) std::cout << e << " "; std::cout << "\n"; } diff --git a/ch12/ex12_10.cpp b/ch12/ex12_10.cpp index 8c0c45bf..b72f28c9 100644 --- a/ch12/ex12_10.cpp +++ b/ch12/ex12_10.cpp @@ -10,13 +10,11 @@ //! 464 is correct. If not, how would you correct the call? // correct. - #include #include #include #include - void process(std::shared_ptr ptr) { std::cout << "inside the process function:" << ptr.use_count() << "\n"; @@ -27,7 +25,6 @@ int main() std::shared_ptr p(new int(42)); process(std::shared_ptr(p)); - /** * codes below shows how the reference count change. */ diff --git a/ch12/ex12_11.cpp b/ch12/ex12_11.cpp index 7bbedcd1..6d8a511b 100644 --- a/ch12/ex12_11.cpp +++ b/ch12/ex12_11.cpp @@ -10,13 +10,11 @@ // An error was generated at run time : double free or corruption. // See the comments below. - #include #include #include #include - void process(std::shared_ptr ptr) { std::cout << "inside the process function:" << ptr.use_count() << "\n"; @@ -27,13 +25,15 @@ int main() std::shared_ptr p(new int(42)); /** - * @brief std::shared_ptr(p.get()) construct a temporary shared_ptr and copy it - * to the parameter.However it is not a copy of p. As a result, at end of this - * main function p will free the memory that has been freed inside process (). + * @brief std::shared_ptr(p.get()) construct a temporary shared_ptr + * and copy it + * to the parameter.However it is not a copy of p. As a result, at + * end of this + * main function p will free the memory that has been freed inside + * process (). * That's why "double freed or corruption" was generated. */ process(std::shared_ptr(p.get())); - return 0; } diff --git a/ch12/ex12_12.cpp b/ch12/ex12_12.cpp index ad4a9075..9c2f6a84 100644 --- a/ch12/ex12_12.cpp +++ b/ch12/ex12_12.cpp @@ -12,13 +12,11 @@ // See comments below. //! - #include #include #include #include - void process(std::shared_ptr ptr) { std::cout << "inside the process function:" << ptr.use_count() << "\n"; @@ -32,27 +30,27 @@ int main() /** @brief * legal. Just copy sp which is a shared_ptr to process(). */ - //process(sp); + // process(sp); /** @brief * illegale.plain pointer can not convert to smart pointer implicitly. */ - //process(new int()); + // process(new int()); /** @brief * illegale.plain pointer can not convert to smart pointer implicitly. */ - //process(p); + // process(p); /** @brief - * Legal. But it's a bad practice to do so. - * Because using smart pointer together with raw pointer could potentially cause problems. + * Legal. But it's a bad practice to do so. + * Because using smart pointer together with raw pointer could potentially + * cause problems. * For example double free as shown in #145. - * + * * Check issue #145 for detail, thx @endyul for reporting */ - //process(std::shared_ptr(p)); - + // process(std::shared_ptr(p)); return 0; } diff --git a/ch12/ex12_14.cpp b/ch12/ex12_14.cpp index 7794fff4..790399bc 100644 --- a/ch12/ex12_14.cpp +++ b/ch12/ex12_14.cpp @@ -5,7 +5,8 @@ // Created by pezy on 12/22/14. // Copyright (c) 2014 pezy. All rights reserved. // -// Write your own version of a function that uses a shared_ptr to manage a connection. +// Write your own version of a function that uses a shared_ptr to manage a +// connection. #include #include @@ -14,32 +15,34 @@ struct connection { std::string ip; int port; - connection(std::string ip_, int port_):ip(ip_), port(port_){ } + connection(std::string ip_, int port_) : ip(ip_), port(port_) {} }; struct destination { std::string ip; int port; - destination(std::string ip_, int port_):ip(ip_), port(port_){ } + destination(std::string ip_, int port_) : ip(ip_), port(port_) {} }; connection connect(destination* pDest) { std::shared_ptr pConn(new connection(pDest->ip, pDest->port)); - std::cout << "creating connection(" << pConn.use_count() << ")" << std::endl; + std::cout << "creating connection(" << pConn.use_count() << ")" + << std::endl; return *pConn; } void disconnect(connection pConn) { - std::cout << "connection close(" << pConn.ip << ":" << pConn.port << ")" << std::endl; + std::cout << "connection close(" << pConn.ip << ":" << pConn.port << ")" + << std::endl; } -void end_connection(connection *pConn) +void end_connection(connection* pConn) { disconnect(*pConn); } -void f(destination &d) +void f(destination& d) { connection conn = connect(&d); std::shared_ptr p(&conn, end_connection); diff --git a/ch12/ex12_15.cpp b/ch12/ex12_15.cpp index 2fdb3314..2c3d7bad 100644 --- a/ch12/ex12_15.cpp +++ b/ch12/ex12_15.cpp @@ -5,7 +5,8 @@ // Created by pezy on 12/22/14. // Copyright (c) 2014 pezy. All rights reserved. // -// Rewrite the first exercise to use a lambda (10.3.2, p.388) in place of the end_connection function. +// Rewrite the first exercise to use a lambda (10.3.2, p.388) in place of the +// end_connection function. #include #include @@ -14,30 +15,32 @@ struct connection { std::string ip; int port; - connection(std::string ip_, int port_):ip(ip_), port(port_){ } + connection(std::string ip_, int port_) : ip(ip_), port(port_) {} }; struct destination { std::string ip; int port; - destination(std::string ip_, int port_):ip(ip_), port(port_){ } + destination(std::string ip_, int port_) : ip(ip_), port(port_) {} }; connection connect(destination* pDest) { std::shared_ptr pConn(new connection(pDest->ip, pDest->port)); - std::cout << "creating connection(" << pConn.use_count() << ")" << std::endl; + std::cout << "creating connection(" << pConn.use_count() << ")" + << std::endl; return *pConn; } void disconnect(connection pConn) { - std::cout << "connection close(" << pConn.ip << ":" << pConn.port << ")" << std::endl; + std::cout << "connection close(" << pConn.ip << ":" << pConn.port << ")" + << std::endl; } -void f(destination &d) +void f(destination& d) { connection conn = connect(&d); - std::shared_ptr p(&conn, [](connection *p){disconnect(*p);}); + std::shared_ptr p(&conn, [](connection* p) { disconnect(*p); }); std::cout << "connecting now(" << p.use_count() << ")" << std::endl; } diff --git a/ch12/ex12_16.cpp b/ch12/ex12_16.cpp index 6dad8714..eff03f97 100644 --- a/ch12/ex12_16.cpp +++ b/ch12/ex12_16.cpp @@ -5,26 +5,31 @@ // Created by pezy on 12/22/14. // Copyright (c) 2014 pezy. All rights reserved. // -// Compilers don’t always give easy-to-understand error messages if we attempt to -// copy or assign a unique_ptr. Write a program that contains these errors to see +// Compilers don’t always give easy-to-understand error messages if we attempt +// to +// copy or assign a unique_ptr. Write a program that contains these errors to +// see // how your compiler diagnoses them. #include #include #include -using std::string; using std::unique_ptr; +using std::string; +using std::unique_ptr; int main() { unique_ptr p1(new string("pezy")); // unique_ptr p2(p1); // copy // ^ - // Error: Call to implicitly-deleted copy constructor of 'unique_ptr' + // Error: Call to implicitly-deleted copy constructor of + // 'unique_ptr' // // unique_ptr p3 = p1; // assign // ^ - // Error: Call to implicitly-deleted copy constructor of 'unique_ptr' + // Error: Call to implicitly-deleted copy constructor of + // 'unique_ptr' std::cout << *p1 << std::endl; p1.reset(nullptr); } \ No newline at end of file diff --git a/ch12/ex12_17_18.cpp b/ch12/ex12_17_18.cpp index 0ba40223..af127011 100644 --- a/ch12/ex12_17_18.cpp +++ b/ch12/ex12_17_18.cpp @@ -17,66 +17,64 @@ // more detail can be found a thread on Stack Overflow: // http://stackoverflow.com/questions/1525764/how-to-release-pointer-from-boostshared-ptr - #include #include #include #include - int main() { int ix = 1024, *pi = &ix, *pi2 = new int(2048); typedef std::unique_ptr IntP; - /** - * @brief error: invalid conversion from 'int' to 'std::unique_ptr::pointer {aka int*}' [-fpermissive] + * @brief error: invalid conversion from 'int' to + * 'std::unique_ptr::pointer {aka int*}' [-fpermissive] */ - //IntP p0(ix); - + // IntP p0(ix); /** * @brief The code below can compile, but will cause error at run time. - * The reason is that when the unique_ptr p1 is out of scope, delete will be called - * to free th object. But the object is not allocate using new.Thus, an error + * The reason is that when the unique_ptr p1 is out of scope, delete + * will be called + * to free th object. But the object is not allocate using new.Thus, + * an error * would be thrown by operating system. * @badcode */ - //IntP p1(pi); - + // IntP p1(pi); /** * @brief This code can compile, but cause a dangling pointer at run time. - * The reason is that the unique_ptr will free the object the raw pointer + * The reason is that the unique_ptr will free the object the raw + * pointer * is pointing to. * @badcode */ //{IntP p2(pi2);} - /** - * @brief When the unique_ptr goes out of scope, it will call delete to free an + * @brief When the unique_ptr goes out of scope, it will call delete to + * free an * obeject not allocated using new. * @badcode */ - //IntP p3(&ix); - + // IntP p3(&ix); /** * @brief Recommended. */ - //IntP p4(new int(2048)); - + // IntP p4(new int(2048)); /** * @brief error: double free or corruption at run time - * two unique_ptr are pointing to the same object. Thus, when both are out of + * two unique_ptr are pointing to the same object. Thus, when both + * are out of * scope, Operating system will throw double free or corruption. * @badcode */ - //IntP p2(new int(555)); - //IntP p5(p2.get()); + // IntP p2(new int(555)); + // IntP p5(p2.get()); return 0; } diff --git a/ch12/ex12_19.cpp b/ch12/ex12_19.cpp index 4b6236d9..6368bf2c 100644 --- a/ch12/ex12_19.cpp +++ b/ch12/ex12_19.cpp @@ -6,7 +6,8 @@ // Copyright (c) 2014 pezy. All rights reserved. // // Define your own version of StrBlobPtr and -// update your StrBlob class with the appropriate friend declaration and begin and end members. +// update your StrBlob class with the appropriate friend declaration and begin +// and end members. // // @See ex12_19.h diff --git a/ch12/ex12_19.h b/ch12/ex12_19.h index 43d55aba..0dbef552 100644 --- a/ch12/ex12_19.h +++ b/ch12/ex12_19.h @@ -6,7 +6,8 @@ // Copyright (c) 2014 pezy. All rights reserved. // // Define your own version of StrBlobPtr and -// update your StrBlob class with the appropriate friend declaration and begin and end members. +// update your StrBlob class with the appropriate friend declaration and begin +// and end members. // // @See ex12_02.h @@ -19,7 +20,8 @@ #include #include -using std::vector; using std::string; +using std::vector; +using std::string; class StrBlobPtr; @@ -31,39 +33,48 @@ class StrBlob { StrBlobPtr begin(); StrBlobPtr end(); - StrBlob():data(std::make_shared>()) { } - StrBlob(std::initializer_list il):data(std::make_shared>(il)) { } + StrBlob() : data(std::make_shared>()) {} + StrBlob(std::initializer_list il) + : data(std::make_shared>(il)) + { + } size_type size() const { return data->size(); } bool empty() const { return data->empty(); } - void push_back(const string &t) { data->push_back(t); } - void pop_back() { + void push_back(const string& t) { data->push_back(t); } + void pop_back() + { check(0, "pop_back on empty StrBlob"); data->pop_back(); } - std::string& front() { + std::string& front() + { check(0, "front on empty StrBlob"); return data->front(); } - std::string& back() { + std::string& back() + { check(0, "back on empty StrBlob"); return data->back(); } - const std::string& front() const { + const std::string& front() const + { check(0, "front on empty StrBlob"); return data->front(); } - const std::string& back() const { + const std::string& back() const + { check(0, "back on empty StrBlob"); return data->back(); } private: - void check(size_type i, const string &msg) const { + void check(size_type i, const string& msg) const + { if (i >= data->size()) throw std::out_of_range(msg); } @@ -73,21 +84,24 @@ class StrBlob { class StrBlobPtr { public: - StrBlobPtr():curr(0) { } - StrBlobPtr(StrBlob &a, size_t sz = 0):wptr(a.data), curr(sz) { } - bool operator!=(const StrBlobPtr& p) {return p.curr != curr; } - string& deref() const { + StrBlobPtr() : curr(0) {} + StrBlobPtr(StrBlob& a, size_t sz = 0) : wptr(a.data), curr(sz) {} + bool operator!=(const StrBlobPtr& p) { return p.curr != curr; } + string& deref() const + { auto p = check(curr, "dereference past end"); return (*p)[curr]; } - StrBlobPtr& incr() { + StrBlobPtr& incr() + { check(curr, "increment past end of StrBlobPtr"); ++curr; return *this; } private: - std::shared_ptr> check(size_t i, const string &msg) const { + std::shared_ptr> check(size_t i, const string& msg) const + { auto ret = wptr.lock(); if (!ret) throw std::runtime_error("unbound StrBlobPtr"); if (i >= ret->size()) throw std::out_of_range(msg); diff --git a/ch12/ex12_20.cpp b/ch12/ex12_20.cpp index 87cdf456..a6589837 100644 --- a/ch12/ex12_20.cpp +++ b/ch12/ex12_20.cpp @@ -16,8 +16,8 @@ int main() { std::ifstream ifs("../data/book.txt"); StrBlob blob; - for (std::string str; std::getline(ifs, str); ) - blob.push_back(str); - for (StrBlobPtr pbeg(blob.begin()), pend(blob.end()); pbeg != pend; pbeg.incr()) + for (std::string str; std::getline(ifs, str);) blob.push_back(str); + for (StrBlobPtr pbeg(blob.begin()), pend(blob.end()); pbeg != pend; + pbeg.incr()) std::cout << pbeg.deref() << std::endl; } \ No newline at end of file diff --git a/ch12/ex12_22.h b/ch12/ex12_22.h index d3c8835d..a4c18fcd 100644 --- a/ch12/ex12_22.h +++ b/ch12/ex12_22.h @@ -20,7 +20,8 @@ #include #include -using std::vector; using std::string; +using std::vector; +using std::string; class ConstStrBlobPtr; @@ -30,41 +31,50 @@ class StrBlob { friend class ConstStrBlobPtr; ConstStrBlobPtr begin() const; // should add const - ConstStrBlobPtr end() const; // should add const + ConstStrBlobPtr end() const; // should add const - StrBlob():data(std::make_shared>()) { } - StrBlob(std::initializer_list il):data(std::make_shared>(il)) { } + StrBlob() : data(std::make_shared>()) {} + StrBlob(std::initializer_list il) + : data(std::make_shared>(il)) + { + } size_type size() const { return data->size(); } bool empty() const { return data->empty(); } - void push_back(const string &t) { data->push_back(t); } - void pop_back() { + void push_back(const string& t) { data->push_back(t); } + void pop_back() + { check(0, "pop_back on empty StrBlob"); data->pop_back(); } - std::string& front() { + std::string& front() + { check(0, "front on empty StrBlob"); return data->front(); } - std::string& back() { + std::string& back() + { check(0, "back on empty StrBlob"); return data->back(); } - const std::string& front() const { + const std::string& front() const + { check(0, "front on empty StrBlob"); return data->front(); } - const std::string& back() const { + const std::string& back() const + { check(0, "back on empty StrBlob"); return data->back(); } private: - void check(size_type i, const string &msg) const { + void check(size_type i, const string& msg) const + { if (i >= data->size()) throw std::out_of_range(msg); } @@ -74,21 +84,24 @@ class StrBlob { class ConstStrBlobPtr { public: - ConstStrBlobPtr():curr(0) { } - ConstStrBlobPtr(const StrBlob &a, size_t sz = 0):wptr(a.data), curr(sz) { } // should add const - bool operator!=(ConstStrBlobPtr& p) {return p.curr != curr; } - const string& deref() const { // return value should add const + ConstStrBlobPtr() : curr(0) {} + ConstStrBlobPtr(const StrBlob& a, size_t sz = 0) : wptr(a.data), curr(sz) {} // should add const + bool operator!=(ConstStrBlobPtr& p) { return p.curr != curr; } + const string& deref() const + { // return value should add const auto p = check(curr, "dereference past end"); return (*p)[curr]; } - ConstStrBlobPtr& incr() { + ConstStrBlobPtr& incr() + { check(curr, "increment past end of StrBlobPtr"); ++curr; return *this; } private: - std::shared_ptr> check(size_t i, const string &msg) const { + std::shared_ptr> check(size_t i, const string& msg) const + { auto ret = wptr.lock(); if (!ret) throw std::runtime_error("unbound StrBlobPtr"); if (i >= ret->size()) throw std::out_of_range(msg); diff --git a/ch12/ex12_23.cpp b/ch12/ex12_23.cpp index 5f6f550e..ea7f4792 100644 --- a/ch12/ex12_23.cpp +++ b/ch12/ex12_23.cpp @@ -1,12 +1,14 @@ // // ex12_23.cpp -// Exercise 12.23 +// Exercise 12.23 // // Created by pezy on 12/30/14. // Copyright (c) 2014 pezy. All rights reserved. // -// Write a program to concatenate two string literals, putting the result in a dynamically allocated array of char. -// Write a program to concatenate two library strings that have the same value as the literals used in the first program. +// Write a program to concatenate two string literals, putting the result in a +// dynamically allocated array of char. +// Write a program to concatenate two library strings that have the same value +// as the literals used in the first program. #include #include @@ -15,12 +17,12 @@ int main() { // dynamically allocated array of char - char *concatenate_string = new char[255](); + char* concatenate_string = new char[255](); strcat(concatenate_string, "hello "); strcat(concatenate_string, "world"); std::cout << concatenate_string << std::endl; - delete [] concatenate_string; - + delete[] concatenate_string; + // std::string std::string str1{"hello "}, str2{"world"}; std::cout << str1 + str2 << std::endl; diff --git a/ch12/ex12_24.cpp b/ch12/ex12_24.cpp index 6a4b8db3..9a6813f7 100644 --- a/ch12/ex12_24.cpp +++ b/ch12/ex12_24.cpp @@ -5,10 +5,11 @@ // Created by pezy on 12/30/14. // Copyright (c) 2014 pezy. All rights reserved. // -// Write a program that reads a string from the standard input into a dynamically allocated character array. +// Write a program that reads a string from the standard input into a +// dynamically allocated character array. // Describe how your program handles varying size inputs. -// Test your program by giving it a string of data that is longer than the array size you've allocated. - +// Test your program by giving it a string of data that is longer than the +// array size you've allocated. #include @@ -18,11 +19,12 @@ int main() std::cout << "How long do you want the string? "; int size{0}; std::cin >> size; - char *input = new char[size+1](); + char* input = new char[size + 1](); std::cin.ignore(); std::cout << "input the string: "; - std::cin.get(input, size+1); + std::cin.get(input, size + 1); std::cout << input; - delete [] input; - // Test: if longer than the array size, we will lost the characters which are out of range. + delete[] input; + // Test: if longer than the array size, we will lost the characters which + // are out of range. } diff --git a/ch12/ex12_26.cpp b/ch12/ex12_26.cpp index dcafb7ed..80c11ee4 100644 --- a/ch12/ex12_26.cpp +++ b/ch12/ex12_26.cpp @@ -1,11 +1,11 @@ // // ex12_26.cpp -// Exercise 12.26 +// Exercise 12.26 // // Created by pezy on 12/30/14. // Copyright (c) 2014 pezy. All rights reserved. // -// Rewrite the program on page 481 using an allocator. +// Rewrite the program on page 481 using an allocator. #include #include @@ -17,11 +17,9 @@ void input_reverse_output_string(int n) auto const p = alloc.allocate(n); std::string s; auto q = p; - while (std::cin >> s && q != p + n) - alloc.construct(q++, s); - - while (q != p) - { + while (std::cin >> s && q != p + n) alloc.construct(q++, s); + + while (q != p) { std::cout << *--q << " "; alloc.destroy(q); } diff --git a/ch12/ex12_27_30.cpp b/ch12/ex12_27_30.cpp index 48a40b2e..de420720 100644 --- a/ch12/ex12_27_30.cpp +++ b/ch12/ex12_27_30.cpp @@ -5,14 +5,15 @@ // Created by pezy on 12/31/14. // Copyright (c) 2014 pezy. All rights reserved. // -// The TextQuery and QueryResult classes use only capabilities that we have already covered. +// The TextQuery and QueryResult classes use only capabilities that we have +// already covered. // Without looking ahead, write your own versions of these classes. #include "ex12_27_30.h" #include #include -TextQuery::TextQuery(std::ifstream &ifs) : input(new vector) +TextQuery::TextQuery(std::ifstream& ifs) : input(new vector) { LineNo lineNo{0}; for (string line; std::getline(ifs, line); ++lineNo) { @@ -20,9 +21,10 @@ TextQuery::TextQuery(std::ifstream &ifs) : input(new vector) 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); + std::remove_copy_if(text.begin(), text.end(), + std::back_inserter(word), ispunct); // use reference avoid count of shared_ptr add. - auto &nos = result[word]; + auto& nos = result[word]; if (!nos) nos.reset(new std::set); nos->insert(lineNo); } @@ -34,14 +36,17 @@ QueryResult TextQuery::query(const string& str) const // use static just allocate once. static shared_ptr> nodate(new std::set); auto found = result.find(str); - if (found == result.end()) return QueryResult(str, nodate, input); - else return QueryResult(str, found->second, input); + if (found == result.end()) + return QueryResult(str, nodate, input); + else + return QueryResult(str, found->second, input); } -std::ostream& print(std::ostream &out, const QueryResult& qr) +std::ostream& print(std::ostream& out, const QueryResult& qr) { - out << qr.word << " occurs " << qr.nos->size() << (qr.nos->size() > 1 ? " times" : " time") << std::endl; + 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; + out << "\t(line " << i + 1 << ") " << qr.input->at(i) << std::endl; return out; } diff --git a/ch12/ex12_27_30.h b/ch12/ex12_27_30.h index dc56c193..e3d31e9a 100644 --- a/ch12/ex12_27_30.h +++ b/ch12/ex12_27_30.h @@ -1,11 +1,12 @@ // -// ex12_27.h +// ex12_27.h // Exercise 12.27 // // Created by pezy on 12/31/14. // Copyright (c) 2014 pezy. All rights reserved. // -// The TextQuery and QueryResult classes use only capabilities that we have already covered. +// The TextQuery and QueryResult classes use only capabilities that we have +// already covered. // Without looking ahead, write your own versions of these classes. #ifndef CP5_ex12_27_h @@ -29,8 +30,9 @@ class QueryResult; class TextQuery { public: using LineNo = vector::size_type; - TextQuery(std::ifstream &); + TextQuery(std::ifstream&); QueryResult query(const string&) const; + private: shared_ptr> input; std::map>> result; @@ -38,15 +40,21 @@ class TextQuery { class QueryResult { public: - friend std::ostream& print(std::ostream &, const QueryResult&); + friend std::ostream& print(std::ostream&, const QueryResult&); + public: - QueryResult(const string &s, shared_ptr> set, shared_ptr> v) : word(s), nos(set), input(v) {} + QueryResult(const string& s, shared_ptr> set, + shared_ptr> v) + : word(s), nos(set), input(v) + { + } + private: string word; shared_ptr> nos; shared_ptr> input; }; -std::ostream& print(std::ostream &, const QueryResult&); +std::ostream& print(std::ostream&, const QueryResult&); #endif diff --git a/ch12/ex12_27_30_TEST.cpp b/ch12/ex12_27_30_TEST.cpp index f914b3ee..09e2560c 100644 --- a/ch12/ex12_27_30_TEST.cpp +++ b/ch12/ex12_27_30_TEST.cpp @@ -5,13 +5,14 @@ // Created by pezy on 12/31/14. // Copyright (c) 2014 pezy. All rights reserved. // -// The TextQuery and QueryResult classes use only capabilities that we have already covered. +// The TextQuery and QueryResult classes use only capabilities that we have +// already covered. // Without looking ahead, write your own versions of these classes. #include "ex12_27_30.h" #include -void runQueries(std::ifstream &infile) +void runQueries(std::ifstream& infile) { TextQuery tq(infile); while (true) { diff --git a/ch12/ex12_28.cpp b/ch12/ex12_28.cpp index cb99f679..fe269455 100644 --- a/ch12/ex12_28.cpp +++ b/ch12/ex12_28.cpp @@ -5,8 +5,10 @@ // Created by pezy on 1/1/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Write a program to implement text queries without defining classes to manage the data. -// Your program should take a file and interact with a user to query for words in that file. +// Write a program to implement text queries without defining classes to manage +// the data. +// Your program should take a file and interact with a user to query for words +// in that file. // Use vector, map, and set containers to hold the data for the file and // to generate the results for the queries. @@ -32,25 +34,31 @@ int main() vector input; std::map> dictionary; decltype(input.size()) lineNo{0}; - + for (string line; std::getline(file, line); ++lineNo) { input.push_back(line); std::istringstream line_stream(line); for (string text, word; line_stream >> text; word.clear()) { - std::remove_copy_if(text.begin(), text.end(), std::back_inserter(word), ispunct); + std::remove_copy_if(text.begin(), text.end(), + std::back_inserter(word), ispunct); dictionary[word].insert(lineNo); } } - + while (true) { std::cout << "enter word to look for, or q to quit: "; string s; if (!(std::cin >> s) || s == "q") break; auto found = dictionary.find(s); if (found != dictionary.end()) { - std::cout << s << " occurs " << found->second.size() << (found->second.size() > 1 ? " times" : " time") << std::endl; + std::cout << s << " occurs " << found->second.size() + << (found->second.size() > 1 ? " times" : " time") + << std::endl; for (auto i : found->second) - std::cout << "\t(line " << i+1 << ") " << input.at(i) << std::endl; - } else std::cout << s << " occurs 0 time" << std::endl; + std::cout << "\t(line " << i + 1 << ") " << input.at(i) + << std::endl; + } + else + std::cout << s << " occurs 0 time" << std::endl; } } diff --git a/ch12/ex12_32.cpp b/ch12/ex12_32.cpp index 1e96e20e..c5ac6ac9 100644 --- a/ch12/ex12_32.cpp +++ b/ch12/ex12_32.cpp @@ -9,10 +9,10 @@ // instead of a vector to hold the input file. #include "ex12_32.h" -#include +#include #include -TextQuery::TextQuery(std::ifstream &ifs) : input(new StrBlob) +TextQuery::TextQuery(std::ifstream& ifs) : input(new StrBlob) { StrBlob::size_type lineNo{0}; for (string line; std::getline(ifs, line); ++lineNo) { @@ -20,30 +20,35 @@ TextQuery::TextQuery(std::ifstream &ifs) : input(new StrBlob) 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); - // use reference avoid count of shared_ptr add. - auto &nos = result[word]; + std::remove_copy_if(text.begin(), text.end(), + std::back_inserter(word), ispunct); + // use reference avoid count of shared_ptr add. + auto& nos = result[word]; if (!nos) nos.reset(new std::set); nos->insert(lineNo); } } } -QueryResult TextQuery::query(const string& str) const +QueryResult TextQuery::query(const string& str) const { // use static just allocate once. - static shared_ptr> nodate(new std::set); + static shared_ptr> nodate( + new std::set); auto found = result.find(str); - if (found == result.end()) return QueryResult(str, nodate, input); - else return QueryResult(str, found->second, input); + if (found == result.end()) + return QueryResult(str, nodate, input); + else + return QueryResult(str, found->second, input); } -std::ostream& print(std::ostream &out, const QueryResult& qr) +std::ostream& print(std::ostream& out, const QueryResult& qr) { - out << qr.word << " occurs " << qr.nos->size() << (qr.nos->size() > 1 ? " times" : " time") << std::endl; + out << qr.word << " occurs " << qr.nos->size() + << (qr.nos->size() > 1 ? " times" : " time") << std::endl; for (auto i : *qr.nos) { ConstStrBlobPtr p(*qr.input, i); - out << "\t(line " << i+1 << ") " << p.deref() << std::endl; + out << "\t(line " << i + 1 << ") " << p.deref() << std::endl; } return out; } diff --git a/ch12/ex12_32.h b/ch12/ex12_32.h index 92de0bc6..ac62e81a 100644 --- a/ch12/ex12_32.h +++ b/ch12/ex12_32.h @@ -22,8 +22,9 @@ using std::shared_ptr; class QueryResult; class TextQuery { public: - TextQuery(std::ifstream &); + TextQuery(std::ifstream&); QueryResult query(const string&) const; + private: shared_ptr input; std::map>> result; @@ -31,15 +32,21 @@ class TextQuery { class QueryResult { public: - friend std::ostream& print(std::ostream &, const QueryResult&); + friend std::ostream& print(std::ostream&, const QueryResult&); + public: - QueryResult(const string &s, shared_ptr> set, shared_ptr v) : word(s), nos(set), input(v) {} + QueryResult(const string& s, shared_ptr> set, + shared_ptr v) + : word(s), nos(set), input(v) + { + } + private: string word; shared_ptr> nos; shared_ptr input; }; -std::ostream& print(std::ostream &, const QueryResult&); +std::ostream& print(std::ostream&, const QueryResult&); #endif diff --git a/ch12/ex12_33.cpp b/ch12/ex12_33.cpp index a4c869d7..d13c009f 100644 --- a/ch12/ex12_33.cpp +++ b/ch12/ex12_33.cpp @@ -9,10 +9,10 @@ // instead of a vector to hold the input file. #include "ex12_33.h" -#include +#include #include -TextQuery::TextQuery(std::ifstream &ifs) : input(new StrBlob) +TextQuery::TextQuery(std::ifstream& ifs) : input(new StrBlob) { StrBlob::size_type lineNo{0}; for (string line; std::getline(ifs, line); ++lineNo) { @@ -20,27 +20,32 @@ TextQuery::TextQuery(std::ifstream &ifs) : input(new StrBlob) 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); - // use reference avoid count of shared_ptr add. - auto &nos = result[word]; + std::remove_copy_if(text.begin(), text.end(), + std::back_inserter(word), ispunct); + // use reference avoid count of shared_ptr add. + auto& nos = result[word]; if (!nos) nos.reset(new std::set); nos->insert(lineNo); } } } -QueryResult TextQuery::query(const string& str) const +QueryResult TextQuery::query(const string& str) const { // use static just allocate once. - static shared_ptr> nodate(new std::set); + static shared_ptr> nodate( + new std::set); auto found = result.find(str); - if (found == result.end()) return QueryResult(str, nodate, input); - else return QueryResult(str, found->second, input); + if (found == result.end()) + return QueryResult(str, nodate, input); + else + return QueryResult(str, found->second, input); } -std::ostream& print(std::ostream &out, const QueryResult& qr) +std::ostream& print(std::ostream& out, const QueryResult& qr) { - out << qr.word << " occurs " << qr.nos->size() << (qr.nos->size() > 1 ? " times" : " time") << std::endl; + out << qr.word << " occurs " << qr.nos->size() + << (qr.nos->size() > 1 ? " times" : " time") << std::endl; for (auto it = qr.begin(); it != qr.end(); ++it) { ConstStrBlobPtr p(*qr.get_file(), *it); out << "\t(line " << *it + 1 << ") " << p.deref() << std::endl; diff --git a/ch12/ex12_33.h b/ch12/ex12_33.h index 478e6e15..447d44b7 100644 --- a/ch12/ex12_33.h +++ b/ch12/ex12_33.h @@ -5,9 +5,11 @@ // Created by pezy on 1/1/15. // Copyright (c) 2015 pezy. All rights reserved. // -// In Chapter 15 we’ll extend our query system and will need some additional members +// In Chapter 15 we’ll extend our query system and will need some additional +// members // in the QueryResult class. -// Add members named [begin] and [end] that return iterators into the set of line numbers +// Add members named [begin] and [end] that return iterators into the set of +// line numbers // returned by a given query, and a member named [get_file] that // returns a shared_ptr to the file in the QueryResult object. @@ -25,8 +27,9 @@ using std::shared_ptr; class QueryResult; class TextQuery { public: - TextQuery(std::ifstream &); + TextQuery(std::ifstream&); QueryResult query(const string&) const; + private: shared_ptr input; std::map>> result; @@ -35,9 +38,14 @@ class TextQuery { class QueryResult { public: using ResultIter = std::set::iterator; - friend std::ostream& print(std::ostream &, const QueryResult&); + friend std::ostream& print(std::ostream&, const QueryResult&); + public: - QueryResult(const string &s, shared_ptr> set, shared_ptr v) : word(s), nos(set), input(v) {} + QueryResult(const string& s, shared_ptr> set, + shared_ptr v) + : word(s), nos(set), input(v) + { + } ResultIter begin() const { return nos->begin(); } ResultIter end() const { return nos->end(); } shared_ptr get_file() const { return input; } @@ -47,6 +55,6 @@ class QueryResult { shared_ptr input; }; -std::ostream& print(std::ostream &, const QueryResult&); +std::ostream& print(std::ostream&, const QueryResult&); #endif diff --git a/ch13/ex13_05.h b/ch13/ex13_05.h index 3670a145..7a2c3d60 100644 --- a/ch13/ex13_05.h +++ b/ch13/ex13_05.h @@ -5,8 +5,10 @@ // Created by pezy on 1/5/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Given the following sketch of a class, write a copy constructor that copies all the members. -// Your constructor should dynamically allocate a new string and copy the object to which ps points, +// Given the following sketch of a class, write a copy constructor that copies +// all the members. +// Your constructor should dynamically allocate a new string and copy the +// object to which ps points, // rather than copying ps itself. #ifndef CP5_ex13_05_h @@ -16,10 +18,12 @@ class HasPtr { public: - 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(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) {} private: - std::string *ps; + std::string* ps; int i; }; diff --git a/ch13/ex13_08.h b/ch13/ex13_08.h index c2e38291..79ba2554 100644 --- a/ch13/ex13_08.h +++ b/ch13/ex13_08.h @@ -5,10 +5,12 @@ // Created by pezy on 1/12/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Write the assignment operator for the HasPtr class from exercise 13.5 in 13.1.1 (p. 499). -// As with the copy constructor, your assignment operator should copy the object to which ps points. +// Write the assignment operator for the HasPtr class from exercise 13.5 in +// 13.1.1 (p. 499). +// As with the copy constructor, your assignment operator should copy the +// object to which ps points. // -// See ex13_05.h +// See ex13_05.h #ifndef CP5_ex13_08_h #define CP5_ex13_08_h @@ -17,17 +19,21 @@ class HasPtr { public: - 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=(const HasPtr &hp) { - std::string *new_ps = new std::string(*hp.ps); + 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=(const HasPtr& hp) + { + std::string* new_ps = new std::string(*hp.ps); delete ps; ps = new_ps; i = hp.i; return *this; } + private: - std::string *ps; + std::string* ps; int i; }; diff --git a/ch13/ex13_11.h b/ch13/ex13_11.h index 87720721..671fb8ad 100644 --- a/ch13/ex13_11.h +++ b/ch13/ex13_11.h @@ -5,9 +5,9 @@ // Created by pezy on 1/13/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Add a destructor to your HasPtr class from the previous exercises. +// Add a destructor to your HasPtr class from the previous exercises. // -// See ex13_08.h +// See ex13_08.h #ifndef CP5_ex13_11_h #define CP5_ex13_11_h @@ -16,20 +16,21 @@ class HasPtr { public: - 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=(const HasPtr &hp) { - std::string *new_ps = new std::string(*hp.ps); + 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=(const HasPtr& hp) + { + std::string* new_ps = new std::string(*hp.ps); delete ps; ps = new_ps; i = hp.i; return *this; } - ~HasPtr() { - delete ps; - } + ~HasPtr() { delete ps; } private: - std::string *ps; + std::string* ps; int i; }; diff --git a/ch13/ex13_13.cpp b/ch13/ex13_13.cpp index 5b23f393..b4935335 100644 --- a/ch13/ex13_13.cpp +++ b/ch13/ex13_13.cpp @@ -5,17 +5,21 @@ // Created by pezy on 1/13/15. // Copyright (c) 2015 pezy. All rights reserved. // -// A good way to understand copy-control members and constructors is to define a simple class with these members in which each member prints its name: +// A good way to understand copy-control members and constructors is to define +// a simple class with these members in which each member prints its name: // struct X { // X() {std::cout << "X()" << std::endl;} // X(const X&) {std::cout << "X(const X&)" << std::endl;} // }; -// Add the copy-assignment operator and destructor to X and write a program using X objects in various ways: +// Add the copy-assignment operator and destructor to X and write a program +// using X objects in various ways: // Pass them as nonreference and reference parameters; // dynamically allocate them; // put them in containers; and so forth. -// Study the output until you are certain you understand when and why each copy-control member is used. -// As you read the output, remember that the compiler can omit calls to the copy constructor. +// Study the output until you are certain you understand when and why each +// copy-control member is used. +// As you read the output, remember that the compiler can omit calls to the +// copy constructor. #include #include @@ -24,11 +28,15 @@ struct X { X() { std::cout << "X()" << std::endl; } X(const X&) { std::cout << "X(const X&)" << std::endl; } - X& operator=(const X&) { std::cout << "X& operator=(const X&)" << std::endl; return *this; } + X& operator=(const X&) + { + std::cout << "X& operator=(const X&)" << std::endl; + return *this; + } ~X() { std::cout << "~X()" << std::endl; } }; -void f(const X &rx, X x) +void f(const X& rx, X x) { std::vector vec; vec.reserve(2); @@ -38,10 +46,9 @@ void f(const X &rx, X x) int main() { - X *px = new X; + X* px = new X; f(*px, *px); delete px; return 0; } - diff --git a/ch13/ex13_17_1.cpp b/ch13/ex13_17_1.cpp index 43924b48..405b9e72 100644 --- a/ch13/ex13_17_1.cpp +++ b/ch13/ex13_17_1.cpp @@ -5,7 +5,8 @@ // Created by pezy on 1/15/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Write versions of numbered and f corresponding to the previous three exercises +// Write versions of numbered and f corresponding to the previous three +// exercises // and check whether you correctly predicted the output. // // For 13.14 @@ -14,7 +15,8 @@ class numbered { public: - numbered() { + numbered() + { static int unique = 10; mysn = unique++; } @@ -22,7 +24,8 @@ class numbered { int mysn; }; -void f(numbered s) { +void f(numbered s) +{ std::cout << s.mysn << std::endl; } diff --git a/ch13/ex13_17_2.cpp b/ch13/ex13_17_2.cpp index 81a92271..c3b84137 100644 --- a/ch13/ex13_17_2.cpp +++ b/ch13/ex13_17_2.cpp @@ -5,7 +5,8 @@ // Created by pezy on 1/15/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Write versions of numbered and f corresponding to the previous three exercises +// Write versions of numbered and f corresponding to the previous three +// exercises // and check whether you correctly predicted the output. // // For 13.15 @@ -14,19 +15,19 @@ class numbered { public: - numbered() { + numbered() + { static int unique = 10; mysn = unique++; } - numbered(const numbered& n) { - mysn = n.mysn + 1; - } + numbered(const numbered& n) { mysn = n.mysn + 1; } int mysn; }; -void f(numbered s) { +void f(numbered s) +{ std::cout << s.mysn << std::endl; } diff --git a/ch13/ex13_17_3.cpp b/ch13/ex13_17_3.cpp index 3b6591b6..4517d5e8 100644 --- a/ch13/ex13_17_3.cpp +++ b/ch13/ex13_17_3.cpp @@ -5,7 +5,8 @@ // Created by pezy on 1/15/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Write versions of numbered and f corresponding to the previous three exercises +// Write versions of numbered and f corresponding to the previous three +// exercises // and check whether you correctly predicted the output. // // For 13.16 @@ -14,19 +15,19 @@ class numbered { public: - numbered() { + numbered() + { static int unique = 10; mysn = unique++; } - numbered(const numbered& n) { - mysn = n.mysn + 1; - } + numbered(const numbered& n) { mysn = n.mysn + 1; } int mysn; }; -void f(const numbered& s) { +void f(const numbered& s) +{ std::cout << s.mysn << std::endl; } diff --git a/ch13/ex13_18.cpp b/ch13/ex13_18.cpp index b1d7cfcd..8c35693d 100644 --- a/ch13/ex13_18.cpp +++ b/ch13/ex13_18.cpp @@ -5,21 +5,25 @@ // Created by pezy on 1/15/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Define an Employee class that contains an employee name and a unique employee identifier. +// Define an Employee class that contains an employee name and a unique +// employee identifier. // Give the class a default constructor and a constructor that // takes a string representing the employee’s name. -// Each constructor should generate a unique ID by incrementing a static data member. +// Each constructor should generate a unique ID by incrementing a static data +// member. // #include "ex13_18.h" int Employee::s_increment = 0; -Employee::Employee() { +Employee::Employee() +{ id_ = s_increment++; } -Employee::Employee(const string &name) { +Employee::Employee(const string& name) +{ id_ = s_increment++; name_ = name; } \ No newline at end of file diff --git a/ch13/ex13_18.h b/ch13/ex13_18.h index ca54b68a..1f2ae170 100644 --- a/ch13/ex13_18.h +++ b/ch13/ex13_18.h @@ -5,10 +5,12 @@ // Created by pezy on 1/15/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Define an Employee class that contains an employee name and a unique employee identifier. +// Define an Employee class that contains an employee name and a unique +// employee identifier. // Give the class a default constructor and a constructor that // takes a string representing the employee’s name. -// Each constructor should generate a unique ID by incrementing a static data member. +// Each constructor should generate a unique ID by incrementing a static data +// member. // #ifndef CP5_ex13_18_h @@ -20,10 +22,10 @@ using std::string; class Employee { public: Employee(); - Employee(const string &name); - + Employee(const string& name); + const int id() const { return id_; } - + private: string name_; int id_; diff --git a/ch13/ex13_19.h b/ch13/ex13_19.h index f6c14538..741186e7 100644 --- a/ch13/ex13_19.h +++ b/ch13/ex13_19.h @@ -5,11 +5,13 @@ // Created by pezy on 1/15/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Does your Employee class need to define its own versions of the copy-control members? +// Does your Employee class need to define its own versions of the copy-control +// members? // If so, why? If not, why not? // Implement whatever copy-control members you think Employee needs. // -// Answer: No, cause there really is no sensible meaning. employee can't copy in real world. +// Answer: No, cause there really is no sensible meaning. employee can't copy +// in real world. #ifndef CP5_ex13_19_h #define CP5_ex13_19_h @@ -20,7 +22,7 @@ using std::string; class Employee { public: Employee(); - Employee(const string &name); + Employee(const string& name); Employee(const Employee&) = delete; Employee& operator=(const Employee&) = delete; diff --git a/ch13/ex13_22.h b/ch13/ex13_22.h index 837a5556..1d54957b 100644 --- a/ch13/ex13_22.h +++ b/ch13/ex13_22.h @@ -5,13 +5,16 @@ // Created by pezy on 1/13/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Assume that we want HasPtr to behave like a value. -// That is, each object should have its own copy of the string to which the objects point. -// We¡¯ll show the definitions of the copy-control members in the next section. -// However, you already know everything you need to know to implement these members. -// Write the HasPtr copy constructor and copyassignment operator before reading on. +// Assume that we want HasPtr to behave like a value. +// That is, each object should have its own copy of the string to which the +// objects point. +// We¡¯ll show the definitions of the copy-control members in the next section. +// However, you already know everything you need to know to implement these +// members. +// Write the HasPtr copy constructor and copyassignment operator before reading +// on. // -// See ex13_11.h +// See ex13_11.h #ifndef CP5_ex13_11_h #define CP5_ex13_11_h @@ -20,20 +23,21 @@ class HasPtr { public: - 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=(const HasPtr &hp) { + 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=(const HasPtr& hp) + { auto new_p = new std::string(*hp.ps); delete ps; ps = new_p; i = hp.i; return *this; } - ~HasPtr() { - delete ps; - } + ~HasPtr() { delete ps; } private: - std::string *ps; + std::string* ps; int i; }; diff --git a/ch13/ex13_26.cpp b/ch13/ex13_26.cpp index a0fee4f7..18a2dc8f 100644 --- a/ch13/ex13_26.cpp +++ b/ch13/ex13_26.cpp @@ -5,7 +5,8 @@ // Created by pezy on 1/19/15. // Copyright (c) 2014 pezy. All rights reserved. // -// Write your own version of the StrBlob class described in the previous exercise. +// Write your own version of the StrBlob class described in the previous +// exercise. // // @See ex12_22 and ex13_25 diff --git a/ch13/ex13_26.h b/ch13/ex13_26.h index 70b3f4ef..1644cb3b 100644 --- a/ch13/ex13_26.h +++ b/ch13/ex13_26.h @@ -5,7 +5,8 @@ // Created by pezy on 1/19/15. // Copyright (c) 2014 pezy. All rights reserved. // -// Write your own version of the StrBlob class described in the previous exercise. +// Write your own version of the StrBlob class described in the previous +// exercise. // // @See ex12_22 and ex13_25 @@ -18,7 +19,8 @@ #include #include -using std::vector; using std::string; +using std::vector; +using std::string; class ConstStrBlobPtr; @@ -30,44 +32,56 @@ class StrBlob { ConstStrBlobPtr begin() const; ConstStrBlobPtr end() const; - StrBlob():data(std::make_shared>()) { } - StrBlob(std::initializer_list il):data(std::make_shared>(il)) { } + StrBlob() : data(std::make_shared>()) {} + StrBlob(std::initializer_list il) + : data(std::make_shared>(il)) + { + } // copy constructor - StrBlob(const StrBlob& sb) : data(std::make_shared>(*sb.data)) {} + StrBlob(const StrBlob& sb) + : data(std::make_shared>(*sb.data)) + { + } // copyassignment operators StrBlob& operator=(const StrBlob& sb); size_type size() const { return data->size(); } bool empty() const { return data->empty(); } - void push_back(const string &t) { data->push_back(t); } - void pop_back() { + void push_back(const string& t) { data->push_back(t); } + void pop_back() + { check(0, "pop_back on empty StrBlob"); data->pop_back(); } - std::string& front() { + std::string& front() + { check(0, "front on empty StrBlob"); return data->front(); } - std::string& back() { + std::string& back() + { check(0, "back on empty StrBlob"); return data->back(); } - const std::string& front() const { + const std::string& front() const + { check(0, "front on empty StrBlob"); return data->front(); } - const std::string& back() const { + const std::string& back() const + { check(0, "back on empty StrBlob"); return data->back(); } private: - void check(size_type i, const string &msg) const { + void check(size_type i, const string& msg) const + { if (i >= data->size()) throw std::out_of_range(msg); } @@ -77,21 +91,24 @@ class StrBlob { class ConstStrBlobPtr { public: - ConstStrBlobPtr():curr(0) { } - ConstStrBlobPtr(const StrBlob &a, size_t sz = 0):wptr(a.data), curr(sz) { } // should add const - bool operator!=(ConstStrBlobPtr& p) {return p.curr != curr; } - const string& deref() const { // return value should add const + ConstStrBlobPtr() : curr(0) {} + ConstStrBlobPtr(const StrBlob& a, size_t sz = 0) : wptr(a.data), curr(sz) {} // should add const + bool operator!=(ConstStrBlobPtr& p) { return p.curr != curr; } + const string& deref() const + { // return value should add const auto p = check(curr, "dereference past end"); return (*p)[curr]; } - ConstStrBlobPtr& incr() { + ConstStrBlobPtr& incr() + { check(curr, "increment past end of StrBlobPtr"); ++curr; return *this; } private: - std::shared_ptr> check(size_t i, const string &msg) const { + std::shared_ptr> check(size_t i, const string& msg) const + { auto ret = wptr.lock(); if (!ret) throw std::runtime_error("unbound StrBlobPtr"); if (i >= ret->size()) throw std::out_of_range(msg); diff --git a/ch13/ex13_27.h b/ch13/ex13_27.h index feb29967..faaf318e 100644 --- a/ch13/ex13_27.h +++ b/ch13/ex13_27.h @@ -5,7 +5,7 @@ // Created by pezy on 1/20/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Define your own reference-counted version of HasPtr. +// Define your own reference-counted version of HasPtr. #ifndef CP5_ex13_27_h #define CP5_ex13_27_h @@ -14,9 +14,13 @@ class HasPtr { public: - HasPtr(const std::string &s = std::string()) : ps(new std::string(s)), i(0), use(new size_t(1)) { } - HasPtr(const HasPtr &hp) : ps(hp.ps), i(hp.i), use(hp.use) { ++*use; } - HasPtr& operator=(const HasPtr &rhs) { + HasPtr(const std::string& s = std::string()) + : ps(new std::string(s)), i(0), use(new size_t(1)) + { + } + HasPtr(const HasPtr& hp) : ps(hp.ps), i(hp.i), use(hp.use) { ++*use; } + HasPtr& operator=(const HasPtr& rhs) + { ++*rhs.use; if (--*use == 0) { delete ps; @@ -27,16 +31,18 @@ class HasPtr { use = rhs.use; return *this; } - ~HasPtr() { + ~HasPtr() + { if (--*use == 0) { delete ps; delete use; } - } + } + private: - std::string *ps; + std::string* ps; int i; - size_t *use; + size_t* use; }; #endif diff --git a/ch13/ex13_28.cpp b/ch13/ex13_28.cpp index a8bef9d7..9c8ab3ad 100644 --- a/ch13/ex13_28.cpp +++ b/ch13/ex13_28.cpp @@ -5,11 +5,12 @@ // Created by pezy on 1/20/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Given the following classes, implement a default constructor and the necessary copy-control members. +// Given the following classes, implement a default constructor and the +// necessary copy-control members. #include "ex13_28.h" -TreeNode& TreeNode::operator=(const TreeNode &rhs) +TreeNode& TreeNode::operator=(const TreeNode& rhs) { ++*rhs.count; if (--*count == 0) { @@ -32,9 +33,9 @@ TreeNode& TreeNode::operator=(const TreeNode &rhs) return *this; } -BinStrTree& BinStrTree::operator=(const BinStrTree &bst) +BinStrTree& BinStrTree::operator=(const BinStrTree& bst) { - TreeNode *new_root = new TreeNode(*bst.root); + TreeNode* new_root = new TreeNode(*bst.root); delete root; root = new_root; return *this; diff --git a/ch13/ex13_28.h b/ch13/ex13_28.h index a19ad6a5..3ed4f2f4 100644 --- a/ch13/ex13_28.h +++ b/ch13/ex13_28.h @@ -5,7 +5,8 @@ // Created by pezy on 1/20/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Given the following classes, implement a default constructor and the necessary copy-control members. +// Given the following classes, implement a default constructor and the +// necessary copy-control members. #ifndef CP5_ex13_28_h #define CP5_ex13_28_h @@ -15,10 +16,18 @@ using std::string; class TreeNode { public: - TreeNode() : value(string()), count(new int(1)), left(nullptr), right(nullptr) {} - TreeNode(const TreeNode &rhs) : value(rhs.value), count(rhs.count), left(rhs.left), right(rhs.right) { ++*count; } - TreeNode& operator=(const TreeNode &rhs); - ~TreeNode() { + TreeNode() + : value(string()), count(new int(1)), left(nullptr), right(nullptr) + { + } + TreeNode(const TreeNode& rhs) + : value(rhs.value), count(rhs.count), left(rhs.left), right(rhs.right) + { + ++*count; + } + TreeNode& operator=(const TreeNode& rhs); + ~TreeNode() + { if (--*count == 0) { if (left) { delete left; @@ -35,20 +44,20 @@ class TreeNode { private: std::string value; - int *count; - TreeNode *left; - TreeNode *right; + int* count; + TreeNode* left; + TreeNode* right; }; class BinStrTree { public: BinStrTree() : root(new TreeNode()) {} - BinStrTree(const BinStrTree &bst) : root(new TreeNode(*bst.root)) {} - BinStrTree& operator=(const BinStrTree &bst); + BinStrTree(const BinStrTree& bst) : root(new TreeNode(*bst.root)) {} + BinStrTree& operator=(const BinStrTree& bst); ~BinStrTree() { delete root; } private: - TreeNode *root; + TreeNode* root; }; #endif diff --git a/ch13/ex13_30.h b/ch13/ex13_30.h index 92daf425..8c5c5135 100644 --- a/ch13/ex13_30.h +++ b/ch13/ex13_30.h @@ -1,14 +1,14 @@ // // ex13_30.h -// Exercise 13.30 +// Exercise 13.30 // // Created by pezy on 1/23/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Write and test a swap function for your valuelike version of HasPtr. -// Give your swap a print statement that notes when it is executed. +// Write and test a swap function for your valuelike version of HasPtr. +// Give your swap a print statement that notes when it is executed. // -// See ex13_22.h +// See ex13_22.h #ifndef CP5_ex13_11_h #define CP5_ex13_11_h @@ -19,22 +19,23 @@ class HasPtr { public: friend void swap(HasPtr&, HasPtr&); - 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=(const HasPtr &hp) { + 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=(const HasPtr& hp) + { auto new_p = new std::string(*hp.ps); delete ps; ps = new_p; i = hp.i; return *this; } - ~HasPtr() { - delete ps; - } - + ~HasPtr() { delete ps; } + void show() { std::cout << *ps << std::endl; } private: - std::string *ps; + std::string* ps; int i; }; diff --git a/ch13/ex13_31.h b/ch13/ex13_31.h index 647b3ca6..647c96dc 100644 --- a/ch13/ex13_31.h +++ b/ch13/ex13_31.h @@ -1,15 +1,15 @@ // // ex13_31.h -// Exercise 13.31 +// 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. +// 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 +// See ex13_30.h #ifndef CP5_ex13_11_h #define CP5_ex13_11_h @@ -20,27 +20,29 @@ 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) { + 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) + { this->swap(tmp); return *this; } - ~HasPtr() { - delete ps; - } - - void swap(HasPtr &rhs) { + ~HasPtr() { delete ps; } + + 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; } private: - std::string *ps; + std::string* ps; int i; }; @@ -49,7 +51,7 @@ void swap(HasPtr& lhs, HasPtr& rhs) lhs.swap(rhs); } -bool operator<(const HasPtr &lhs, const HasPtr &rhs) +bool operator<(const HasPtr& lhs, const HasPtr& rhs) { return *lhs.ps < *rhs.ps; } diff --git a/ch13/ex13_34_36_37.cpp b/ch13/ex13_34_36_37.cpp index fc193f27..0842ba59 100644 --- a/ch13/ex13_34_36_37.cpp +++ b/ch13/ex13_34_36_37.cpp @@ -1,52 +1,46 @@ #include "ex13_34_36_37.h" #include -void swap(Message &lhs, Message &rhs) +void swap(Message& lhs, Message& rhs) { using std::swap; - for (auto f : lhs.folders) - f->remMsg(&lhs); - for (auto f : rhs.folders) - f->remMsg(&rhs); + for (auto f : lhs.folders) f->remMsg(&lhs); + for (auto f : rhs.folders) f->remMsg(&rhs); swap(lhs.folders, rhs.folders); swap(lhs.contents, rhs.contents); - for (auto f : lhs.folders) - f->addMsg(&lhs); - for (auto f : rhs.folders) - f->addMsg(&rhs); + for (auto f : lhs.folders) f->addMsg(&lhs); + for (auto f : rhs.folders) f->addMsg(&rhs); } // Message Implementation -void Message::save(Folder &f) +void Message::save(Folder& f) { folders.insert(&f); f.addMsg(this); } -void Message::remove(Folder &f) +void Message::remove(Folder& f) { folders.erase(&f); f.remMsg(this); } -void Message::add_to_Folders(const Message &m) +void Message::add_to_Folders(const Message& m) { - for (auto f : m.folders) - f->addMsg(this); + for (auto f : m.folders) f->addMsg(this); } -Message::Message(const Message &m) : contents(m.contents), folders(m.folders) +Message::Message(const Message& m) : contents(m.contents), folders(m.folders) { add_to_Folders(m); } void Message::remove_from_Folders() { - for (auto f : folders) - f->remMsg(this); + for (auto f : folders) f->remMsg(this); } Message::~Message() @@ -54,7 +48,7 @@ Message::~Message() remove_from_Folders(); } -Message& Message::operator=(const Message &rhs) +Message& Message::operator=(const Message& rhs) { remove_from_Folders(); contents = rhs.contents; @@ -70,39 +64,33 @@ void Message::print_debug() // Folder Implementation -void swap(Folder &lhs, Folder &rhs) +void swap(Folder& lhs, Folder& rhs) { - using std::swap; - for (auto m : lhs.msgs) - m->remFldr(&lhs); + using std::swap; + for (auto m : lhs.msgs) m->remFldr(&lhs); - for (auto m : rhs.msgs) - m->remFldr(&rhs); + for (auto m : rhs.msgs) m->remFldr(&rhs); - swap(lhs.msgs, rhs.msgs); + swap(lhs.msgs, rhs.msgs); - for (auto m : lhs.msgs) - m->addFldr(&lhs); + for (auto m : lhs.msgs) m->addFldr(&lhs); - for (auto m : rhs.msgs) - m->addFldr(&rhs); + for (auto m : rhs.msgs) m->addFldr(&rhs); } -void Folder::add_to_Message(const Folder &f) +void Folder::add_to_Message(const Folder& f) { - for (auto m : f.msgs) - m->addFldr(this); + for (auto m : f.msgs) m->addFldr(this); } -Folder::Folder(const Folder &f) : msgs(f.msgs) +Folder::Folder(const Folder& f) : msgs(f.msgs) { add_to_Message(f); } void Folder::remove_to_Message() { - for (auto m : msgs) - m->remFldr(this); + for (auto m : msgs) m->remFldr(this); } Folder::~Folder() @@ -110,7 +98,7 @@ Folder::~Folder() remove_to_Message(); } -Folder& Folder::operator =(const Folder &rhs) +Folder& Folder::operator=(const Folder& rhs) { remove_to_Message(); msgs = rhs.msgs; @@ -120,7 +108,6 @@ Folder& Folder::operator =(const Folder &rhs) void Folder::print_debug() { - for (auto m : msgs) - std::cout << m->contents << " "; + for (auto m : msgs) std::cout << m->contents << " "; std::cout << std::endl; } diff --git a/ch13/ex13_34_36_37.h b/ch13/ex13_34_36_37.h index 875db79e..e7a592b3 100644 --- a/ch13/ex13_34_36_37.h +++ b/ch13/ex13_34_36_37.h @@ -7,9 +7,11 @@ // // 34: Write the Message class as described in this section. // -// 36: Design and implement the corresponding Folder class. That class should hold a set that points to the Messages in that Folder. +// 36: Design and implement the corresponding Folder class. That class should +// hold a set that points to the Messages in that Folder. // -// 37: Add members to the Message class to insert or remove a given Folder* into folders. +// 37: Add members to the Message class to insert or remove a given Folder* +// into folders. // These members are analogous to Folder’s addMsg and remMsg operations. #ifndef CP5_ex13_34_36_37_h @@ -21,11 +23,12 @@ class Folder; class Message { - friend void swap(Message &, Message &); - friend void swap(Folder &, Folder &); + friend void swap(Message&, Message&); + friend void swap(Folder&, Folder&); friend class Folder; + public: - explicit Message(const std::string &str = ""):contents(str) {} + explicit Message(const std::string& str = "") : contents(str) {} Message(const Message&); Message& operator=(const Message&); ~Message(); @@ -41,20 +44,21 @@ class Message { void add_to_Folders(const Message&); void remove_from_Folders(); - void addFldr(Folder *f) { folders.insert(f); } - void remFldr(Folder *f) { folders.erase(f); } + void addFldr(Folder* f) { folders.insert(f); } + void remFldr(Folder* f) { folders.erase(f); } }; void swap(Message&, Message&); class Folder { friend void swap(Message&, Message&); - friend void swap(Folder &, Folder &); + friend void swap(Folder&, Folder&); friend class Message; + public: Folder() = default; - Folder(const Folder &); - Folder& operator=(const Folder &); + Folder(const Folder&); + Folder& operator=(const Folder&); ~Folder(); void print_debug(); @@ -65,11 +69,10 @@ class Folder { void add_to_Message(const Folder&); void remove_to_Message(); - void addMsg(Message *m) { msgs.insert(m); } - void remMsg(Message *m) { msgs.erase(m); } + void addMsg(Message* m) { msgs.insert(m); } + void remMsg(Message* m) { msgs.erase(m); } }; -void swap(Folder &, Folder &); +void swap(Folder&, Folder&); #endif // MESSAGE - diff --git a/ch13/ex13_39.cpp b/ch13/ex13_39.cpp index 29fb30d0..08e3b876 100644 --- a/ch13/ex13_39.cpp +++ b/ch13/ex13_39.cpp @@ -11,88 +11,86 @@ #include "ex13_39.h" -void StrVec::push_back(const std::string &s) +void StrVec::push_back(const std::string& s) { - chk_n_alloc(); - alloc.construct(first_free++, s); + chk_n_alloc(); + alloc.construct(first_free++, s); } -std::pair -StrVec::alloc_n_copy(const std::string *b, const std::string *e) +std::pair StrVec::alloc_n_copy(const std::string* b, + const std::string* e) { - auto data = alloc.allocate(e-b); - return { data, std::uninitialized_copy(b, e, data) }; + auto data = alloc.allocate(e - b); + return {data, std::uninitialized_copy(b, e, data)}; } void StrVec::free() { - if (elements) { - for (auto p = first_free; p != elements;) - alloc.destroy(--p); - alloc.deallocate(elements, cap - elements); - } + if (elements) { + for (auto p = first_free; p != elements;) alloc.destroy(--p); + alloc.deallocate(elements, cap - elements); + } } -StrVec::StrVec(const StrVec &rhs) +StrVec::StrVec(const StrVec& rhs) { - auto newdata = alloc_n_copy(rhs.begin(), rhs.end()); - elements = newdata.first; - first_free = cap = newdata.second; + auto newdata = alloc_n_copy(rhs.begin(), rhs.end()); + elements = newdata.first; + first_free = cap = newdata.second; } StrVec::~StrVec() { - free(); + free(); } -StrVec& StrVec::operator = (const StrVec &rhs) +StrVec& StrVec::operator=(const StrVec& rhs) { - auto data = alloc_n_copy(rhs.begin(), rhs.end()); - free(); - elements = data.first; - first_free = cap = data.second; - return *this; + auto data = alloc_n_copy(rhs.begin(), rhs.end()); + free(); + elements = data.first; + first_free = cap = data.second; + return *this; } void StrVec::alloc_n_move(size_t new_cap) { - auto newdata = alloc.allocate(new_cap); - auto dest = newdata; - auto elem = elements; - for (size_t i = 0; i != size(); ++i) - alloc.construct(dest++, std::move(*elem++)); - free(); - elements = newdata; - first_free = dest; - cap = elements + new_cap; + auto newdata = alloc.allocate(new_cap); + auto dest = newdata; + auto elem = elements; + for (size_t i = 0; i != size(); ++i) + alloc.construct(dest++, std::move(*elem++)); + free(); + elements = newdata; + first_free = dest; + cap = elements + new_cap; } void StrVec::reallocate() { - auto newcapacity = size() ? 2 * size() : 1; - alloc_n_move(newcapacity); + auto newcapacity = size() ? 2 * size() : 1; + alloc_n_move(newcapacity); } void StrVec::reserve(size_t new_cap) { - if (new_cap <= capacity()) return; - alloc_n_move(new_cap); + if (new_cap <= capacity()) return; + alloc_n_move(new_cap); } void StrVec::resize(size_t count) { - resize(count, std::string()); + resize(count, std::string()); } -void StrVec::resize(size_t count, const std::string &s) +void StrVec::resize(size_t count, const std::string& s) { - if (count > size()) { - if (count > capacity()) reserve(count * 2); - for (size_t i = size(); i != count; ++i) - alloc.construct(first_free++, s); - } - else if (count < size()) { - while (first_free != elements + count) - alloc.destroy(--first_free); - } + if (count > size()) { + if (count > capacity()) reserve(count * 2); + for (size_t i = size(); i != count; ++i) + alloc.construct(first_free++, s); + } + else if (count < size()) { + while (first_free != elements + count) alloc.destroy(--first_free); + } } diff --git a/ch13/ex13_39.h b/ch13/ex13_39.h index 007d9bb1..227946ed 100644 --- a/ch13/ex13_39.h +++ b/ch13/ex13_39.h @@ -1,12 +1,12 @@ // // ex13_39.h -// Exercise 13.39 +// Exercise 13.39 // // Created by pezy on 2/3/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Write your own version of StrVec, including versions of -// reserve, capacity (9.4, p. 356), and resize (9.3.5, p. 352). +// Write your own version of StrVec, including versions of +// reserve, capacity (9.4, p. 356), and resize (9.3.5, p. 352). // #ifndef CP5_EX_13_39_H_ @@ -15,37 +15,39 @@ #include #include -class StrVec -{ +class StrVec { public: - StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} - StrVec(const StrVec&); - StrVec& operator=(const StrVec&); - ~StrVec(); + StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} + StrVec(const StrVec&); + StrVec& operator=(const StrVec&); + ~StrVec(); - void push_back(const std::string&); - size_t size() const { return first_free - elements; } - size_t capacity() const { return cap - elements; } - std::string *begin() const { return elements; } - std::string *end() const { return first_free; } + void push_back(const std::string&); + size_t size() const { return first_free - elements; } + size_t capacity() const { return cap - elements; } + std::string* begin() const { return elements; } + std::string* end() const { return first_free; } - void reserve(size_t new_cap); - void resize(size_t count); - void resize(size_t count, const std::string&); + void reserve(size_t new_cap); + void resize(size_t count); + void resize(size_t count, const std::string&); private: - std::pair alloc_n_copy(const std::string*, const std::string*); - void free(); - void chk_n_alloc() { if (size() == capacity()) reallocate(); } - void reallocate(); - void alloc_n_move(size_t new_cap); + std::pair alloc_n_copy(const std::string*, + const std::string*); + void free(); + void chk_n_alloc() + { + if (size() == capacity()) reallocate(); + } + void reallocate(); + void alloc_n_move(size_t new_cap); private: - std::string *elements; - std::string *first_free; - std::string *cap; - std::allocator alloc; + std::string* elements; + std::string* first_free; + std::string* cap; + std::allocator alloc; }; #endif - diff --git a/ch13/ex13_40.cpp b/ch13/ex13_40.cpp index 8109f186..15e525b5 100644 --- a/ch13/ex13_40.cpp +++ b/ch13/ex13_40.cpp @@ -5,103 +5,102 @@ // Created by pezy on 2/3/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Add a constructor that takes an initializer_list to your StrVec class. +// Add a constructor that takes an initializer_list to your StrVec +// class. // #include "ex13_40.h" -void StrVec::push_back(const std::string &s) +void StrVec::push_back(const std::string& s) { - chk_n_alloc(); - alloc.construct(first_free++, s); + chk_n_alloc(); + alloc.construct(first_free++, s); } -std::pair -StrVec::alloc_n_copy(const std::string *b, const std::string *e) +std::pair StrVec::alloc_n_copy(const std::string* b, + const std::string* e) { - auto data = alloc.allocate(e-b); - return { data, std::uninitialized_copy(b, e, data) }; + auto data = alloc.allocate(e - b); + return {data, std::uninitialized_copy(b, e, data)}; } void StrVec::free() { - if (elements) { - for (auto p = first_free; p != elements;) - alloc.destroy(--p); - alloc.deallocate(elements, cap - elements); - } + if (elements) { + for (auto p = first_free; p != elements;) alloc.destroy(--p); + alloc.deallocate(elements, cap - elements); + } } -void StrVec::range_initialize(const std::string *first, const std::string *last) +void StrVec::range_initialize(const std::string* first, const std::string* last) { - auto newdata = alloc_n_copy(first, last); - elements = newdata.first; - first_free = cap = newdata.second; + auto newdata = alloc_n_copy(first, last); + elements = newdata.first; + first_free = cap = newdata.second; } -StrVec::StrVec(const StrVec &rhs) +StrVec::StrVec(const StrVec& rhs) { - range_initialize(rhs.begin(), rhs.end()); + range_initialize(rhs.begin(), rhs.end()); } StrVec::StrVec(std::initializer_list il) { - range_initialize(il.begin(), il.end()); + range_initialize(il.begin(), il.end()); } StrVec::~StrVec() { - free(); + free(); } -StrVec& StrVec::operator = (const StrVec &rhs) +StrVec& StrVec::operator=(const StrVec& rhs) { - auto data = alloc_n_copy(rhs.begin(), rhs.end()); - free(); - elements = data.first; - first_free = cap = data.second; - return *this; + auto data = alloc_n_copy(rhs.begin(), rhs.end()); + free(); + elements = data.first; + first_free = cap = data.second; + return *this; } void StrVec::alloc_n_move(size_t new_cap) { - auto newdata = alloc.allocate(new_cap); - auto dest = newdata; - auto elem = elements; - for (size_t i = 0; i != size(); ++i) - alloc.construct(dest++, std::move(*elem++)); - free(); - elements = newdata; - first_free = dest; - cap = elements + new_cap; + auto newdata = alloc.allocate(new_cap); + auto dest = newdata; + auto elem = elements; + for (size_t i = 0; i != size(); ++i) + alloc.construct(dest++, std::move(*elem++)); + free(); + elements = newdata; + first_free = dest; + cap = elements + new_cap; } void StrVec::reallocate() { - auto newcapacity = size() ? 2 * size() : 1; - alloc_n_move(newcapacity); + auto newcapacity = size() ? 2 * size() : 1; + alloc_n_move(newcapacity); } void StrVec::reserve(size_t new_cap) { - if (new_cap <= capacity()) return; - alloc_n_move(new_cap); + if (new_cap <= capacity()) return; + alloc_n_move(new_cap); } void StrVec::resize(size_t count) { - resize(count, std::string()); + resize(count, std::string()); } -void StrVec::resize(size_t count, const std::string &s) +void StrVec::resize(size_t count, const std::string& s) { - if (count > size()) { - if (count > capacity()) reserve(count * 2); - for (size_t i = size(); i != count; ++i) - alloc.construct(first_free++, s); - } - else if (count < size()) { - while (first_free != elements + count) - alloc.destroy(--first_free); - } + if (count > size()) { + if (count > capacity()) reserve(count * 2); + for (size_t i = size(); i != count; ++i) + alloc.construct(first_free++, s); + } + else if (count < size()) { + while (first_free != elements + count) alloc.destroy(--first_free); + } } diff --git a/ch13/ex13_40.h b/ch13/ex13_40.h index 3a79b3c2..c230f480 100644 --- a/ch13/ex13_40.h +++ b/ch13/ex13_40.h @@ -5,7 +5,8 @@ // Created by pezy on 2/3/15. // Copyright (c) 2015 pezy. All rights reserved. // -// Add a constructor that takes an initializer_list to your StrVec class. +// Add a constructor that takes an initializer_list to your StrVec +// class. // #ifndef CP5_EX_13_40_H_ @@ -15,39 +16,41 @@ #include #include -class StrVec -{ +class StrVec { public: - StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} - StrVec(const StrVec&); - StrVec(std::initializer_list); - StrVec& operator=(const StrVec&); - ~StrVec(); - - void push_back(const std::string&); - size_t size() const { return first_free - elements; } - size_t capacity() const { return cap - elements; } - std::string *begin() const { return elements; } - std::string *end() const { return first_free; } - - void reserve(size_t new_cap); - void resize(size_t count); - void resize(size_t count, const std::string&); + StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} + StrVec(const StrVec&); + StrVec(std::initializer_list); + StrVec& operator=(const StrVec&); + ~StrVec(); + + void push_back(const std::string&); + size_t size() const { return first_free - elements; } + size_t capacity() const { return cap - elements; } + std::string* begin() const { return elements; } + std::string* end() const { return first_free; } + + void reserve(size_t new_cap); + void resize(size_t count); + void resize(size_t count, const std::string&); private: - std::pair alloc_n_copy(const std::string*, const std::string*); - void free(); - void chk_n_alloc() { if (size() == capacity()) reallocate(); } - void reallocate(); - void alloc_n_move(size_t new_cap); - void range_initialize(const std::string*, const std::string*); + std::pair alloc_n_copy(const std::string*, + const std::string*); + void free(); + void chk_n_alloc() + { + if (size() == capacity()) reallocate(); + } + void reallocate(); + void alloc_n_move(size_t new_cap); + void range_initialize(const std::string*, const std::string*); private: - std::string *elements; - std::string *first_free; - std::string *cap; - std::allocator alloc; + std::string* elements; + std::string* first_free; + std::string* cap; + std::allocator alloc; }; #endif - diff --git a/ch13/ex13_42.cpp b/ch13/ex13_42.cpp index e7053ca9..d95258e4 100644 --- a/ch13/ex13_42.cpp +++ b/ch13/ex13_42.cpp @@ -1,7 +1,7 @@ #include "ex13_42_TextQuery.h" #include -void runQueries(std::ifstream &infile) +void runQueries(std::ifstream& infile) { TextQuery tq(infile); while (true) { diff --git a/ch13/ex13_42_StrVec.cpp b/ch13/ex13_42_StrVec.cpp index 467b5404..b3a34b10 100644 --- a/ch13/ex13_42_StrVec.cpp +++ b/ch13/ex13_42_StrVec.cpp @@ -1,97 +1,95 @@ #include "ex13_42_StrVec.h" -void StrVec::push_back(const std::string &s) +void StrVec::push_back(const std::string& s) { - chk_n_alloc(); - alloc.construct(first_free++, s); + chk_n_alloc(); + alloc.construct(first_free++, s); } -std::pair -StrVec::alloc_n_copy(const std::string *b, const std::string *e) +std::pair StrVec::alloc_n_copy(const std::string* b, + const std::string* e) { - auto data = alloc.allocate(e-b); - return { data, std::uninitialized_copy(b, e, data) }; + auto data = alloc.allocate(e - b); + return {data, std::uninitialized_copy(b, e, data)}; } void StrVec::free() { - if (elements) { - for (auto p = first_free; p != elements;) - alloc.destroy(--p); - alloc.deallocate(elements, cap - elements); - } + if (elements) { + for (auto p = first_free; p != elements;) alloc.destroy(--p); + alloc.deallocate(elements, cap - elements); + } } -void StrVec::range_initialize(const std::string *first, const std::string *last) +void StrVec::range_initialize(const std::string* first, const std::string* last) { - auto newdata = alloc_n_copy(first, last); - elements = newdata.first; - first_free = cap = newdata.second; + auto newdata = alloc_n_copy(first, last); + elements = newdata.first; + first_free = cap = newdata.second; } -StrVec::StrVec(const StrVec &rhs) +StrVec::StrVec(const StrVec& rhs) { - range_initialize(rhs.begin(), rhs.end()); + range_initialize(rhs.begin(), rhs.end()); } StrVec::StrVec(std::initializer_list il) { - range_initialize(il.begin(), il.end()); + range_initialize(il.begin(), il.end()); } StrVec::~StrVec() { - free(); + free(); } -StrVec& StrVec::operator = (const StrVec &rhs) +StrVec& StrVec::operator=(const StrVec& rhs) { - auto data = alloc_n_copy(rhs.begin(), rhs.end()); - free(); - elements = data.first; - first_free = cap = data.second; - return *this; + auto data = alloc_n_copy(rhs.begin(), rhs.end()); + free(); + elements = data.first; + first_free = cap = data.second; + return *this; } void StrVec::alloc_n_move(size_t new_cap) { - auto newdata = alloc.allocate(new_cap); - auto dest = newdata; - auto elem = elements; - for (size_t i = 0; i != size(); ++i) - alloc.construct(dest++, std::move(*elem++)); - free(); - elements = newdata; - first_free = dest; - cap = elements + new_cap; + auto newdata = alloc.allocate(new_cap); + auto dest = newdata; + auto elem = elements; + for (size_t i = 0; i != size(); ++i) + alloc.construct(dest++, std::move(*elem++)); + free(); + elements = newdata; + first_free = dest; + cap = elements + new_cap; } void StrVec::reallocate() { - auto newcapacity = size() ? 2 * size() : 1; - alloc_n_move(newcapacity); + auto newcapacity = size() ? 2 * size() : 1; + alloc_n_move(newcapacity); } void StrVec::reserve(size_t new_cap) { - if (new_cap <= capacity()) return; - alloc_n_move(new_cap); + if (new_cap <= capacity()) return; + alloc_n_move(new_cap); } void StrVec::resize(size_t count) { - resize(count, std::string()); + resize(count, std::string()); } -void StrVec::resize(size_t count, const std::string &s) +void StrVec::resize(size_t count, const std::string& s) { - if (count > size()) { - if (count > capacity()) reserve(count * 2); - for (size_t i = size(); i != count; ++i) - alloc.construct(first_free++, s); - } - else if (count < size()) { - while (first_free != elements + count) - alloc.destroy(--first_free); - } + if (count > size()) { + if (count > capacity()) reserve(count * 2); + for (size_t i = size(); i != count; ++i) + alloc.construct(first_free++, s); + } + else if (count < size()) { + while (first_free != elements + count) alloc.destroy(--first_free); + } } diff --git a/ch13/ex13_42_StrVec.h b/ch13/ex13_42_StrVec.h index bd6e89ee..d4900d7e 100644 --- a/ch13/ex13_42_StrVec.h +++ b/ch13/ex13_42_StrVec.h @@ -5,42 +5,44 @@ #include #include -class StrVec -{ +class StrVec { public: - StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} - StrVec(const StrVec&); - StrVec(std::initializer_list); - StrVec& operator=(const StrVec&); - ~StrVec(); + StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} + StrVec(const StrVec&); + StrVec(std::initializer_list); + StrVec& operator=(const StrVec&); + ~StrVec(); - void push_back(const std::string&); - size_t size() const { return first_free - elements; } - size_t capacity() const { return cap - elements; } - std::string *begin() const { return elements; } - std::string *end() const { return first_free; } + void push_back(const std::string&); + size_t size() const { return first_free - elements; } + size_t capacity() const { return cap - elements; } + std::string* begin() const { return elements; } + std::string* end() const { return first_free; } - std::string& at(size_t pos) { return *(elements + pos); } - const std::string& at(size_t pos) const { return *(elements + pos); } + std::string& at(size_t pos) { return *(elements + pos); } + const std::string& at(size_t pos) const { return *(elements + pos); } - void reserve(size_t new_cap); - void resize(size_t count); - void resize(size_t count, const std::string&); + void reserve(size_t new_cap); + void resize(size_t count); + void resize(size_t count, const std::string&); private: - std::pair alloc_n_copy(const std::string*, const std::string*); - void free(); - void chk_n_alloc() { if (size() == capacity()) reallocate(); } - void reallocate(); - void alloc_n_move(size_t new_cap); - void range_initialize(const std::string*, const std::string*); + std::pair alloc_n_copy(const std::string*, + const std::string*); + void free(); + void chk_n_alloc() + { + if (size() == capacity()) reallocate(); + } + void reallocate(); + void alloc_n_move(size_t new_cap); + void range_initialize(const std::string*, const std::string*); private: - std::string *elements; - std::string *first_free; - std::string *cap; - std::allocator alloc; + std::string* elements; + std::string* first_free; + std::string* cap; + std::allocator alloc; }; #endif - diff --git a/ch13/ex13_42_TextQuery.cpp b/ch13/ex13_42_TextQuery.cpp index 55246ac6..b286d0da 100644 --- a/ch13/ex13_42_TextQuery.cpp +++ b/ch13/ex13_42_TextQuery.cpp @@ -4,7 +4,7 @@ using std::string; -TextQuery::TextQuery(std::ifstream &ifs) : input(new StrVec) +TextQuery::TextQuery(std::ifstream& ifs) : input(new StrVec) { size_t lineNo = 0; for (string line; std::getline(ifs, line); ++lineNo) { @@ -12,9 +12,10 @@ TextQuery::TextQuery(std::ifstream &ifs) : input(new StrVec) 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); + std::remove_copy_if(text.begin(), text.end(), + std::back_inserter(word), ispunct); // use reference avoid count of shared_ptr add. - auto &nos = result[word]; + auto& nos = result[word]; if (!nos) nos.reset(new std::set); nos->insert(lineNo); } @@ -24,16 +25,19 @@ TextQuery::TextQuery(std::ifstream &ifs) : input(new StrVec) QueryResult TextQuery::query(const string& str) const { // use static just allocate once. - static std::shared_ptr> nodate(new std::set); + static std::shared_ptr> nodate(new std::set); auto found = result.find(str); - if (found == result.end()) return QueryResult(str, nodate, input); - else return QueryResult(str, found->second, input); + if (found == result.end()) + return QueryResult(str, nodate, input); + else + return QueryResult(str, found->second, input); } -std::ostream& print(std::ostream &out, const QueryResult& qr) +std::ostream& print(std::ostream& out, const QueryResult& qr) { - out << qr.word << " occurs " << qr.nos->size() << (qr.nos->size() > 1 ? " times" : " time") << std::endl; + 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; + out << "\t(line " << i + 1 << ") " << qr.input->at(i) << std::endl; return out; } diff --git a/ch13/ex13_42_TextQuery.h b/ch13/ex13_42_TextQuery.h index 55ddffe6..14ad7584 100644 --- a/ch13/ex13_42_TextQuery.h +++ b/ch13/ex13_42_TextQuery.h @@ -13,24 +13,31 @@ class QueryResult; class TextQuery { public: - TextQuery(std::ifstream &); + TextQuery(std::ifstream&); QueryResult query(const std::string&) const; + private: std::shared_ptr input; - std::map>> result; + std::map>> result; }; class QueryResult { public: - friend std::ostream& print(std::ostream &, const QueryResult&); + friend std::ostream& print(std::ostream&, const QueryResult&); + public: - QueryResult(const std::string &s, std::shared_ptr> set, std::shared_ptr v) : word(s), nos(set), input(v) {} + QueryResult(const std::string& s, std::shared_ptr> set, + std::shared_ptr v) + : word(s), nos(set), input(v) + { + } + private: std::string word; std::shared_ptr> nos; std::shared_ptr input; }; -std::ostream& print(std::ostream &, const QueryResult&); +std::ostream& print(std::ostream&, const QueryResult&); #endif diff --git a/ch13/ex13_44_47.cpp b/ch13/ex13_44_47.cpp index e32b02a6..29e761aa 100644 --- a/ch13/ex13_44_47.cpp +++ b/ch13/ex13_44_47.cpp @@ -2,53 +2,51 @@ #include #include -std::pair -String::alloc_n_copy(const char *b, const char *e) +std::pair String::alloc_n_copy(const char* b, const char* e) { - auto str = alloc.allocate(e-b); - return{ str, std::uninitialized_copy(b, e, str)}; + auto str = alloc.allocate(e - b); + return {str, std::uninitialized_copy(b, e, str)}; } -void String::range_initializer(const char *first, const char *last) +void String::range_initializer(const char* first, const char* last) { - auto newstr = alloc_n_copy(first, last); - elements = newstr.first; - end = newstr.second; + auto newstr = alloc_n_copy(first, last); + elements = newstr.first; + end = newstr.second; } -String::String(const char *s) +String::String(const char* s) { - char *sl = const_cast(s); - while (*sl) - ++sl; - range_initializer(s, ++sl); + char* sl = const_cast(s); + while (*sl) ++sl; + range_initializer(s, ++sl); } String::String(const String& rhs) { - range_initializer(rhs.elements, rhs.end); + range_initializer(rhs.elements, rhs.end); std::cout << "copy constructor" << std::endl; } void String::free() { - if (elements) { - std::for_each(elements, end, [this](char &c){ alloc.destroy(&c); }); - alloc.deallocate(elements, end - elements); - } + if (elements) { + std::for_each(elements, end, [this](char& c) { alloc.destroy(&c); }); + alloc.deallocate(elements, end - elements); + } } String::~String() { - free(); + free(); } -String& String::operator = (const String &rhs) +String& String::operator=(const String& rhs) { - auto newstr = alloc_n_copy(rhs.elements, rhs.end); - free(); - elements = newstr.first; - end = newstr.second; + auto newstr = alloc_n_copy(rhs.elements, rhs.end); + free(); + elements = newstr.first; + end = newstr.second; std::cout << "copy-assignment" << std::endl; - return *this; + return *this; } diff --git a/ch13/ex13_44_47.h b/ch13/ex13_44_47.h index f14f0ff4..717b4ddd 100644 --- a/ch13/ex13_44_47.h +++ b/ch13/ex13_44_47.h @@ -3,29 +3,27 @@ #include -class String -{ +class String { public: - String() : String("") {} - String(const char *); - String(const String&); - String& operator=(const String&); - ~String(); + String() : String("") {} + String(const char*); + String(const String&); + String& operator=(const String&); + ~String(); - const char *c_str() const { return elements; } - size_t size() const { return end - elements; } - size_t length() const { return end - elements - 1; } + const char* c_str() const { return elements; } + size_t size() const { return end - elements; } + size_t length() const { return end - elements - 1; } private: - std::pair alloc_n_copy(const char*, const char*); - void range_initializer(const char*, const char*); - void free(); + std::pair alloc_n_copy(const char*, const char*); + void range_initializer(const char*, const char*); + void free(); private: - char *elements; - char *end; - std::allocator alloc; + char* elements; + char* end; + std::allocator alloc; }; #endif - diff --git a/ch13/ex13_48.cpp b/ch13/ex13_48.cpp index 34bc3a4c..51485aed 100644 --- a/ch13/ex13_48.cpp +++ b/ch13/ex13_48.cpp @@ -16,39 +16,39 @@ void bar(const String& x) String baz() { - String ret("world"); - return ret; + String ret("world"); + return ret; } int main() { - char text[] = "world"; - - String s0; - String s1("hello"); - String s2(s0); - String s3 = s1; - String s4(text); - s2 = s1; - - foo(s1); - bar(s1); - foo("temporary"); - bar("temporary"); - String s5 = baz(); - - std::vector svec; + char text[] = "world"; + + String s0; + String s1("hello"); + String s2(s0); + String s3 = s1; + String s4(text); + s2 = s1; + + foo(s1); + bar(s1); + foo("temporary"); + bar("temporary"); + String s5 = baz(); + + std::vector svec; svec.reserve(8); - svec.push_back(s0); - svec.push_back(s1); - svec.push_back(s2); - svec.push_back(s3); - svec.push_back(s4); + svec.push_back(s0); + svec.push_back(s1); + svec.push_back(s2); + svec.push_back(s3); + svec.push_back(s4); svec.push_back(s5); - svec.push_back(baz()); - svec.push_back("good job"); + svec.push_back(baz()); + svec.push_back("good job"); - for (const auto &s : svec) { - std::cout << s.c_str() << std::endl; - } + for (const auto& s : svec) { + std::cout << s.c_str() << std::endl; + } } diff --git a/ch13/ex13_49_Message.cpp b/ch13/ex13_49_Message.cpp index 3708c627..2da7a293 100644 --- a/ch13/ex13_49_Message.cpp +++ b/ch13/ex13_49_Message.cpp @@ -1,167 +1,153 @@ #include "ex13_49_Message.h" #include -void swap(Message &lhs, Message &rhs) +void swap(Message& lhs, Message& rhs) { - using std::swap; - for (auto f : lhs.folders) - f->remMsg(&lhs); - std::cout << "Remove message from folders" << std::endl; // debug + using std::swap; + for (auto f : lhs.folders) f->remMsg(&lhs); + std::cout << "Remove message from folders" << std::endl; // debug - for (auto f : rhs.folders) - f->remMsg(&rhs); - std::cout << "Remove message from folders" << std::endl; // debug + for (auto f : rhs.folders) f->remMsg(&rhs); + std::cout << "Remove message from folders" << std::endl; // debug - swap(lhs.folders, rhs.folders); - swap(lhs.contents, rhs.contents); + swap(lhs.folders, rhs.folders); + swap(lhs.contents, rhs.contents); - std::cout << "Message members swaped" << std::endl; // debug + std::cout << "Message members swaped" << std::endl; // debug - for (auto f : lhs.folders) - f->addMsg(&lhs); - std::cout << "Added message to folders" << std::endl; // debug + for (auto f : lhs.folders) f->addMsg(&lhs); + std::cout << "Added message to folders" << std::endl; // debug - for (auto f : rhs.folders) - f->addMsg(&rhs); - std::cout << "Added message to folders" << std::endl; // debug + for (auto f : rhs.folders) f->addMsg(&rhs); + std::cout << "Added message to folders" << std::endl; // debug } -Message::Message(const Message &m) : contents(m.contents), folders(m.folders) +Message::Message(const Message& m) : contents(m.contents), folders(m.folders) { - add_to_Folders(m); + add_to_Folders(m); } Message::~Message() { - remove_from_Folders(); + remove_from_Folders(); } -void Message::save(Folder &f) +void Message::save(Folder& f) { - folders.insert(&f); - f.addMsg(this); + folders.insert(&f); + f.addMsg(this); } -void Message::remove(Folder &f) +void Message::remove(Folder& f) { - folders.erase(&f); - f.remMsg(this); + folders.erase(&f); + f.remMsg(this); } -void Message::add_to_Folders(const Message &m) +void Message::add_to_Folders(const Message& m) { - for (auto f : m.folders) - f->addMsg(this); - std::cout << "Added message to folders" << std::endl; // debug + for (auto f : m.folders) f->addMsg(this); + std::cout << "Added message to folders" << std::endl; // debug } void Message::remove_from_Folders() { - for (auto f : folders) - f->remMsg(this); - std::cout << "Remove message from folders" << std::endl; // debug + for (auto f : folders) f->remMsg(this); + std::cout << "Remove message from folders" << std::endl; // debug } -Message& Message::operator=(const Message &rhs) +Message& Message::operator=(const Message& rhs) { - remove_from_Folders(); - contents = rhs.contents; - folders = rhs.folders; - std::cout << "Message members assgined" << std::endl; // debug - add_to_Folders(rhs); - return *this; + remove_from_Folders(); + contents = rhs.contents; + folders = rhs.folders; + std::cout << "Message members assgined" << std::endl; // debug + add_to_Folders(rhs); + return *this; } void Message::print_debug() { - std::cout << contents << ": "; - for (auto f : folders) - std::cout << f->fldr() << " "; - std::cout << std::endl; + std::cout << contents << ": "; + for (auto f : folders) std::cout << f->fldr() << " "; + std::cout << std::endl; } -Message& Message::operator = (Message &&rhs) NOEXCEPT +Message& Message::operator=(Message&& rhs) NOEXCEPT { - remove_from_Folders(); - contents = std::move(rhs.contents); - folders = std::move(rhs.folders); - std::cout << "Message members moved" << std::endl; // debug - return *this; + remove_from_Folders(); + contents = std::move(rhs.contents); + folders = std::move(rhs.folders); + std::cout << "Message members moved" << std::endl; // debug + return *this; } // Folder Implementation -void swap(Folder &lhs, Folder &rhs) +void swap(Folder& lhs, Folder& rhs) { - using std::swap; - for (auto m : lhs.msgs) - m->remFldr(&lhs); - std::cout << "clear folder" << std::endl; // debug + using std::swap; + for (auto m : lhs.msgs) m->remFldr(&lhs); + std::cout << "clear folder" << std::endl; // debug - for (auto m : rhs.msgs) - m->remFldr(&rhs); - std::cout << "clear folder" << std::endl; // debug + for (auto m : rhs.msgs) m->remFldr(&rhs); + std::cout << "clear folder" << std::endl; // debug - swap(lhs.name, rhs.name); - swap(lhs.msgs, rhs.msgs); - std::cout << "Folder members swaped" << std::endl; // debug + swap(lhs.name, rhs.name); + swap(lhs.msgs, rhs.msgs); + std::cout << "Folder members swaped" << std::endl; // debug - for (auto m : lhs.msgs) - m->addFldr(&lhs); - std::cout << "Added messages to folder" << std::endl; // debug + for (auto m : lhs.msgs) m->addFldr(&lhs); + std::cout << "Added messages to folder" << std::endl; // debug - for (auto m : rhs.msgs) - m->addFldr(&rhs); - std::cout << "Added messages to folder" << std::endl; // debug + for (auto m : rhs.msgs) m->addFldr(&rhs); + std::cout << "Added messages to folder" << std::endl; // debug } -void Folder::add_to_Message(const Folder &f) +void Folder::add_to_Message(const Folder& f) { - for (auto m : f.msgs) - m->addFldr(this); - std::cout << "Added messages to folder" << std::endl; // debug + for (auto m : f.msgs) m->addFldr(this); + std::cout << "Added messages to folder" << std::endl; // debug } -Folder::Folder(const Folder &f) : name(f.name), msgs(f.msgs) +Folder::Folder(const Folder& f) : name(f.name), msgs(f.msgs) { - add_to_Message(f); + add_to_Message(f); } void Folder::remove_from_Message() { - for (auto m : msgs) - m->remFldr(this); - std::cout << "clear folder" << std::endl; // debug + for (auto m : msgs) m->remFldr(this); + std::cout << "clear folder" << std::endl; // debug } Folder::~Folder() { - remove_from_Message(); + remove_from_Message(); } -Folder& Folder::operator =(const Folder &rhs) +Folder& Folder::operator=(const Folder& rhs) { - remove_from_Message(); - name = rhs.name; - msgs = rhs.msgs; - std::cout << "Folder members assigned" << std::endl; // debug - add_to_Message(rhs); - return *this; + remove_from_Message(); + name = rhs.name; + msgs = rhs.msgs; + std::cout << "Folder members assigned" << std::endl; // debug + add_to_Message(rhs); + return *this; } void Folder::print_debug() { - std::cout << name << ": "; - for (auto m : msgs) - std::cout << m->msg() << " "; - std::cout << std::endl; + std::cout << name << ": "; + for (auto m : msgs) std::cout << m->msg() << " "; + std::cout << std::endl; } -Folder& Folder::operator=(Folder &&rhs) NOEXCEPT +Folder& Folder::operator=(Folder&& rhs) NOEXCEPT { - remove_from_Message(); - name = std::move(rhs.name); - msgs = std::move(rhs.msgs); - std::cout << "Folder members moved" << std::endl; // debug - return *this; + remove_from_Message(); + name = std::move(rhs.name); + msgs = std::move(rhs.msgs); + std::cout << "Folder members moved" << std::endl; // debug + return *this; } diff --git a/ch13/ex13_49_Message.h b/ch13/ex13_49_Message.h index 06523654..16f276c4 100644 --- a/ch13/ex13_49_Message.h +++ b/ch13/ex13_49_Message.h @@ -12,66 +12,72 @@ class Folder; -class Message -{ - friend void swap(Message &, Message &); - friend void swap(Folder &, Folder &); - friend class Folder; -public: - explicit Message(const std::string &str = "") : contents(str) {} - Message(const Message&); - Message& operator=(const Message&); - Message(Message &&m) NOEXCEPT : contents(std::move(m.contents)), folders(std::move(m.folders)) {} - Message& operator=(Message&&) NOEXCEPT; - ~Message(); - - void save(Folder&); - void remove(Folder&); +class Message { + friend void swap(Message&, Message&); + friend void swap(Folder&, Folder&); + friend class Folder; - const std::string& msg() const { return contents; } - void print_debug(); +public: + explicit Message(const std::string& str = "") : contents(str) {} + Message(const Message&); + Message& operator=(const Message&); + Message(Message&& m) NOEXCEPT : contents(std::move(m.contents)), + folders(std::move(m.folders)) + { + } + Message& operator=(Message&&) NOEXCEPT; + ~Message(); + + void save(Folder&); + void remove(Folder&); + + const std::string& msg() const { return contents; } + void print_debug(); private: - void add_to_Folders(const Message&); - void remove_from_Folders(); + void add_to_Folders(const Message&); + void remove_from_Folders(); - void addFldr(Folder *f) { folders.insert(f); } - void remFldr(Folder *f) { folders.erase(f); } + void addFldr(Folder* f) { folders.insert(f); } + void remFldr(Folder* f) { folders.erase(f); } private: - std::string contents; - std::set folders; + std::string contents; + std::set folders; }; void swap(Message&, Message&); class Folder { - friend void swap(Message&, Message&); - friend void swap(Folder &, Folder &); - friend class Message; -public: - explicit Folder(const std::string &str = "") :name(str) {} - Folder(const Folder &); - Folder& operator=(const Folder &); - Folder(Folder &&f) NOEXCEPT : name(std::move(f.name)), msgs(std::move(f.msgs)) {} - Folder& operator=(Folder &&) NOEXCEPT; - ~Folder(); + friend void swap(Message&, Message&); + friend void swap(Folder&, Folder&); + friend class Message; - const std::string& fldr() const { return name; } - void print_debug(); +public: + explicit Folder(const std::string& str = "") : name(str) {} + Folder(const Folder&); + Folder& operator=(const Folder&); + Folder(Folder&& f) NOEXCEPT : name(std::move(f.name)), + msgs(std::move(f.msgs)) + { + } + Folder& operator=(Folder&&) NOEXCEPT; + ~Folder(); + + const std::string& fldr() const { return name; } + void print_debug(); private: - std::string name; - std::set msgs; + std::string name; + std::set msgs; - void add_to_Message(const Folder&); - void remove_from_Message(); + void add_to_Message(const Folder&); + void remove_from_Message(); - void addMsg(Message *m) { msgs.insert(m); } - void remMsg(Message *m) { msgs.erase(m); } + void addMsg(Message* m) { msgs.insert(m); } + void remMsg(Message* m) { msgs.erase(m); } }; -void swap(Folder &, Folder &); +void swap(Folder&, Folder&); #endif - diff --git a/ch13/ex13_49_StrVec.cpp b/ch13/ex13_49_StrVec.cpp index 1b4c879f..6bb78e6b 100644 --- a/ch13/ex13_49_StrVec.cpp +++ b/ch13/ex13_49_StrVec.cpp @@ -1,115 +1,117 @@ #include "ex13_49_StrVec.h" #include // for_each -void StrVec::push_back(const std::string &s) +void StrVec::push_back(const std::string& s) { - chk_n_alloc(); - alloc.construct(first_free++, s); + chk_n_alloc(); + alloc.construct(first_free++, s); } -std::pair -StrVec::alloc_n_copy(const std::string *b, const std::string *e) +std::pair StrVec::alloc_n_copy(const std::string* b, + const std::string* e) { - auto data = alloc.allocate(e-b); - return { data, std::uninitialized_copy(b, e, data) }; + auto data = alloc.allocate(e - b); + return {data, std::uninitialized_copy(b, e, data)}; } void StrVec::free() { - if (elements) { - for_each(elements, first_free, [this](std::string &rhs){ alloc.destroy(&rhs); }); - alloc.deallocate(elements, cap - elements); - } + if (elements) { + for_each(elements, first_free, + [this](std::string& rhs) { alloc.destroy(&rhs); }); + alloc.deallocate(elements, cap - elements); + } } -void StrVec::range_initialize(const std::string *first, const std::string *last) +void StrVec::range_initialize(const std::string* first, const std::string* last) { - auto newdata = alloc_n_copy(first, last); - elements = newdata.first; - first_free = cap = newdata.second; + auto newdata = alloc_n_copy(first, last); + elements = newdata.first; + first_free = cap = newdata.second; } -StrVec::StrVec(const StrVec &rhs) +StrVec::StrVec(const StrVec& rhs) { - range_initialize(rhs.begin(), rhs.end()); + range_initialize(rhs.begin(), rhs.end()); } StrVec::StrVec(std::initializer_list il) { - range_initialize(il.begin(), il.end()); + range_initialize(il.begin(), il.end()); } StrVec::~StrVec() { - free(); + free(); } -StrVec& StrVec::operator = (const StrVec &rhs) +StrVec& StrVec::operator=(const StrVec& rhs) { - auto data = alloc_n_copy(rhs.begin(), rhs.end()); - free(); - elements = data.first; - first_free = cap = data.second; - return *this; + auto data = alloc_n_copy(rhs.begin(), rhs.end()); + free(); + elements = data.first; + first_free = cap = data.second; + return *this; } void StrVec::alloc_n_move(size_t new_cap) { - auto newdata = alloc.allocate(new_cap); - auto dest = newdata; - auto elem = elements; - for (size_t i = 0; i != size(); ++i) - alloc.construct(dest++, std::move(*elem++)); - free(); - elements = newdata; - first_free = dest; - cap = elements + new_cap; + auto newdata = alloc.allocate(new_cap); + auto dest = newdata; + auto elem = elements; + for (size_t i = 0; i != size(); ++i) + alloc.construct(dest++, std::move(*elem++)); + free(); + elements = newdata; + first_free = dest; + cap = elements + new_cap; } void StrVec::reallocate() { - auto newcapacity = size() ? 2 * size() : 1; - alloc_n_move(newcapacity); + auto newcapacity = size() ? 2 * size() : 1; + alloc_n_move(newcapacity); } void StrVec::reserve(size_t new_cap) { - if (new_cap <= capacity()) return; - alloc_n_move(new_cap); + if (new_cap <= capacity()) return; + alloc_n_move(new_cap); } void StrVec::resize(size_t count) { - resize(count, std::string()); + resize(count, std::string()); } -void StrVec::resize(size_t count, const std::string &s) +void StrVec::resize(size_t count, const std::string& s) { - if (count > size()) { - if (count > capacity()) reserve(count * 2); - for (size_t i = size(); i != count; ++i) - alloc.construct(first_free++, s); - } - else if (count < size()) { - while (first_free != elements + count) - alloc.destroy(--first_free); - } + if (count > size()) { + if (count > capacity()) reserve(count * 2); + for (size_t i = size(); i != count; ++i) + alloc.construct(first_free++, s); + } + else if (count < size()) { + while (first_free != elements + count) alloc.destroy(--first_free); + } } -StrVec::StrVec(StrVec &&s) NOEXCEPT : elements(s.elements), first_free(s.first_free), cap(s.cap) +StrVec::StrVec(StrVec&& s) NOEXCEPT : elements(s.elements), + first_free(s.first_free), + cap(s.cap) { - // leave s in a state in which it is safe to run the destructor. - s.elements = s.first_free = s.cap = nullptr; + // leave s in a state in which it is safe to run the destructor. + s.elements = s.first_free = s.cap = nullptr; } -StrVec& StrVec::operator = (StrVec &&rhs) NOEXCEPT +StrVec& StrVec::operator=(StrVec&& rhs) NOEXCEPT { - if (this != &rhs) { - free(); - elements = rhs.elements; - first_free = rhs.first_free; - cap = rhs.cap; - rhs.elements = rhs.first_free = rhs.cap = nullptr; - } - return *this; + if (this != &rhs) { + free(); + elements = rhs.elements; + first_free = rhs.first_free; + cap = rhs.cap; + rhs.elements = rhs.first_free = rhs.cap = nullptr; + } + return *this; } diff --git a/ch13/ex13_49_StrVec.h b/ch13/ex13_49_StrVec.h index bc698642..419ebe6f 100644 --- a/ch13/ex13_49_StrVec.h +++ b/ch13/ex13_49_StrVec.h @@ -11,44 +11,46 @@ #define NOEXCEPT #endif -class StrVec -{ +class StrVec { public: - StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} - StrVec(std::initializer_list); - StrVec(const StrVec&); - StrVec& operator=(const StrVec&); - StrVec(StrVec&&) NOEXCEPT; - StrVec& operator=(StrVec&&) NOEXCEPT; - ~StrVec(); - - void push_back(const std::string&); - size_t size() const { return first_free - elements; } - size_t capacity() const { return cap - elements; } - std::string *begin() const { return elements; } - std::string *end() const { return first_free; } - - std::string& at(size_t pos) { return *(elements + pos); } - const std::string& at(size_t pos) const { return *(elements + pos); } - - void reserve(size_t new_cap); - void resize(size_t count); - void resize(size_t count, const std::string&); + StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} + StrVec(std::initializer_list); + StrVec(const StrVec&); + StrVec& operator=(const StrVec&); + StrVec(StrVec&&) NOEXCEPT; + StrVec& operator=(StrVec&&) NOEXCEPT; + ~StrVec(); + + void push_back(const std::string&); + size_t size() const { return first_free - elements; } + size_t capacity() const { return cap - elements; } + std::string* begin() const { return elements; } + std::string* end() const { return first_free; } + + std::string& at(size_t pos) { return *(elements + pos); } + const std::string& at(size_t pos) const { return *(elements + pos); } + + void reserve(size_t new_cap); + void resize(size_t count); + void resize(size_t count, const std::string&); private: - std::pair alloc_n_copy(const std::string*, const std::string*); - void free(); - void chk_n_alloc() { if (size() == capacity()) reallocate(); } - void reallocate(); - void alloc_n_move(size_t new_cap); - void range_initialize(const std::string*, const std::string*); + std::pair alloc_n_copy(const std::string*, + const std::string*); + void free(); + void chk_n_alloc() + { + if (size() == capacity()) reallocate(); + } + void reallocate(); + void alloc_n_move(size_t new_cap); + void range_initialize(const std::string*, const std::string*); private: - std::string *elements; - std::string *first_free; - std::string *cap; - std::allocator alloc; + std::string* elements; + std::string* first_free; + std::string* cap; + std::allocator alloc; }; #endif - diff --git a/ch13/ex13_49_String.cpp b/ch13/ex13_49_String.cpp index 10a908ac..96f46d19 100644 --- a/ch13/ex13_49_String.cpp +++ b/ch13/ex13_49_String.cpp @@ -1,67 +1,65 @@ #include "ex13_49_String.h" #include -std::pair -String::alloc_n_copy(const char *b, const char *e) +std::pair String::alloc_n_copy(const char* b, const char* e) { - auto str = alloc.allocate(e-b); - return{ str, std::uninitialized_copy(b, e, str)}; + auto str = alloc.allocate(e - b); + return {str, std::uninitialized_copy(b, e, str)}; } -void String::range_initializer(const char *first, const char *last) +void String::range_initializer(const char* first, const char* last) { - auto newstr = alloc_n_copy(first, last); - elements = newstr.first; - end = newstr.second; + auto newstr = alloc_n_copy(first, last); + elements = newstr.first; + end = newstr.second; } -String::String(const char *s) +String::String(const char* s) { - char *sl = const_cast(s); - while (*sl) - ++sl; - range_initializer(s, ++sl); + char* sl = const_cast(s); + while (*sl) ++sl; + range_initializer(s, ++sl); } String::String(const String& rhs) { - range_initializer(rhs.elements, rhs.end); + range_initializer(rhs.elements, rhs.end); } void String::free() { - if (elements) { - std::for_each(elements, end, [this](char &c){ alloc.destroy(&c); }); - alloc.deallocate(elements, end - elements); - } + if (elements) { + std::for_each(elements, end, [this](char& c) { alloc.destroy(&c); }); + alloc.deallocate(elements, end - elements); + } } String::~String() { - free(); + free(); } -String& String::operator = (const String &rhs) +String& String::operator=(const String& rhs) { - auto newstr = alloc_n_copy(rhs.elements, rhs.end); - free(); - elements = newstr.first; - end = newstr.second; - return *this; + auto newstr = alloc_n_copy(rhs.elements, rhs.end); + free(); + elements = newstr.first; + end = newstr.second; + return *this; } -String::String(String &&s) NOEXCEPT : elements(s.elements), end(s.end) +String::String(String&& s) NOEXCEPT : elements(s.elements), end(s.end) { - s.elements = s.end = nullptr; + s.elements = s.end = nullptr; } -String& String::operator = (String &&rhs) NOEXCEPT +String& String::operator=(String&& rhs) NOEXCEPT { - if (this != &rhs) { - free(); - elements = rhs.elements; - end = rhs.end; - rhs.elements = rhs.end = nullptr; - } - return *this; + if (this != &rhs) { + free(); + elements = rhs.elements; + end = rhs.end; + rhs.elements = rhs.end = nullptr; + } + return *this; } diff --git a/ch13/ex13_49_String.h b/ch13/ex13_49_String.h index 6d40cd0b..c456d04d 100644 --- a/ch13/ex13_49_String.h +++ b/ch13/ex13_49_String.h @@ -9,31 +9,29 @@ #define NOEXCEPT #endif -class String -{ +class String { public: - String() : String("") {} - String(const char *); - String(const String&); - String& operator=(const String&); - String(String &&) NOEXCEPT; - String& operator=(String&&) NOEXCEPT; - ~String(); - - const char *c_str() const { return elements; } - size_t size() const { return end - elements; } - size_t length() const { return end - elements - 1; } + String() : String("") {} + String(const char*); + String(const String&); + String& operator=(const String&); + String(String&&) NOEXCEPT; + String& operator=(String&&) NOEXCEPT; + ~String(); + + const char* c_str() const { return elements; } + size_t size() const { return end - elements; } + size_t length() const { return end - elements - 1; } private: - std::pair alloc_n_copy(const char*, const char*); - void range_initializer(const char*, const char*); - void free(); + std::pair alloc_n_copy(const char*, const char*); + void range_initializer(const char*, const char*); + void free(); private: - char *elements; - char *end; - std::allocator alloc; + char* elements; + char* end; + std::allocator alloc; }; #endif - diff --git a/ch13/ex13_53.cpp b/ch13/ex13_53.cpp index c0773efb..e8fbbf6d 100644 --- a/ch13/ex13_53.cpp +++ b/ch13/ex13_53.cpp @@ -1,7 +1,7 @@ #include "ex13_53.h" #include -inline void swap(HasPtr &lhs, HasPtr &rhs) +inline void swap(HasPtr& lhs, HasPtr& rhs) { using std::swap; swap(lhs.ps, rhs.ps); @@ -9,17 +9,17 @@ inline void swap(HasPtr &lhs, HasPtr &rhs) std::cout << "call swap" << std::endl; } -HasPtr::HasPtr(const std::string &s) : ps(new std::string(s)), i(0) +HasPtr::HasPtr(const std::string& s) : ps(new std::string(s)), i(0) { std::cout << "call constructor" << std::endl; } -HasPtr::HasPtr(const HasPtr &hp) : ps(new std::string(*hp.ps)), i(hp.i) +HasPtr::HasPtr(const HasPtr& hp) : ps(new std::string(*hp.ps)), i(hp.i) { std::cout << "call copy constructor" << std::endl; } -HasPtr::HasPtr(HasPtr &&p) noexcept : ps(p.ps), i(p.i) +HasPtr::HasPtr(HasPtr&& p) noexcept : ps(p.ps), i(p.i) { p.ps = 0; std::cout << "call move constructor" << std::endl; @@ -31,7 +31,7 @@ HasPtr& HasPtr::operator=(HasPtr rhs) return *this; } -//HasPtr& HasPtr::operator=(const HasPtr &rhs) +// HasPtr& HasPtr::operator=(const HasPtr &rhs) //{ // auto newp = new std::string(*rhs.ps); // delete ps; @@ -41,7 +41,7 @@ HasPtr& HasPtr::operator=(HasPtr rhs) // return *this; //} -//HasPtr& HasPtr::operator=(HasPtr &&rhs) noexcept +// HasPtr& HasPtr::operator=(HasPtr &&rhs) noexcept //{ // if (this != &rhs) // { diff --git a/ch13/ex13_53.h b/ch13/ex13_53.h index 315c5fce..982780cc 100644 --- a/ch13/ex13_53.h +++ b/ch13/ex13_53.h @@ -6,16 +6,16 @@ class HasPtr { public: friend void swap(HasPtr&, HasPtr&); - HasPtr(const std::string &s = std::string()); - HasPtr(const HasPtr &hp); - HasPtr(HasPtr &&p) noexcept; + HasPtr(const std::string& s = std::string()); + HasPtr(const HasPtr& hp); + HasPtr(HasPtr&& p) noexcept; HasPtr& operator=(HasPtr rhs); - //HasPtr& operator=(const HasPtr &rhs); - //HasPtr& operator=(HasPtr &&rhs) noexcept; + // HasPtr& operator=(const HasPtr &rhs); + // HasPtr& operator=(HasPtr &&rhs) noexcept; ~HasPtr(); private: - std::string *ps; + std::string* ps; int i; }; diff --git a/ch13/ex13_53_test.cpp b/ch13/ex13_53_test.cpp index 57fea60b..7235cb31 100644 --- a/ch13/ex13_53_test.cpp +++ b/ch13/ex13_53_test.cpp @@ -9,24 +9,24 @@ int main() // when used copy-and-swap -//call constructor -//call constructor -//call constructor -//call copy constructor !!! -//call swap !!! -//call destructor !!! -//call move constructor !!! -//call swap !!! -//call destructor !!! -//call destructor -//call destructor +// call constructor +// call constructor +// call constructor +// call copy constructor !!! +// call swap !!! +// call destructor !!! +// call move constructor !!! +// call swap !!! +// call destructor !!! +// call destructor +// call destructor // when used two assignment operator. -//call constructor -//call constructor -//call constructor -//call copy assignment !!! -//call move assignment !!! -//call destructor -//call destructor +// call constructor +// call constructor +// call constructor +// call copy assignment !!! +// call move assignment !!! +// call destructor +// call destructor diff --git a/ch13/ex13_58.cpp b/ch13/ex13_58.cpp index 7762f27c..7d4f7be8 100644 --- a/ch13/ex13_58.cpp +++ b/ch13/ex13_58.cpp @@ -2,32 +2,36 @@ #include #include -using std::vector; using std::sort; +using std::vector; +using std::sort; class Foo { public: - Foo sorted() &&; - Foo sorted() const &; + Foo sorted()&&; + Foo sorted() const&; + private: vector data; }; -Foo Foo::sorted() && { +Foo Foo::sorted() && +{ sort(data.begin(), data.end()); std::cout << "&&" << std::endl; // debug return *this; } -Foo Foo::sorted() const & { -// Foo ret(*this); -// sort(ret.data.begin(), ret.data.end()); -// return ret; +Foo Foo::sorted() const & +{ + // Foo ret(*this); + // sort(ret.data.begin(), ret.data.end()); + // return ret; std::cout << "const &" << std::endl; // debug -// Foo ret(*this); -// ret.sorted(); // Exercise 13.56 -// return ret; + // Foo ret(*this); + // ret.sorted(); // Exercise 13.56 + // return ret; return Foo(*this).sorted(); // Exercise 13.57 } diff --git a/ch14/ex14_02.cpp b/ch14/ex14_02.cpp index 260fb5a9..1e99bf53 100644 --- a/ch14/ex14_02.cpp +++ b/ch14/ex14_02.cpp @@ -10,19 +10,19 @@ #include "ex14_02.h" -Sales_data::Sales_data(std::istream &is) : Sales_data() +Sales_data::Sales_data(std::istream& is) : Sales_data() { is >> *this; } -Sales_data& Sales_data::operator+=(const Sales_data &rhs) +Sales_data& Sales_data::operator+=(const Sales_data& rhs) { units_sold += rhs.units_sold; revenue += rhs.revenue; return *this; } -std::istream& operator>>(std::istream &is, Sales_data &item) +std::istream& operator>>(std::istream& is, Sales_data& item) { double price = 0.0; is >> item.bookNo >> item.units_sold >> price; @@ -33,13 +33,14 @@ std::istream& operator>>(std::istream &is, Sales_data &item) return is; } -std::ostream& operator<<(std::ostream &os, const Sales_data &item) +std::ostream& operator<<(std::ostream& os, const Sales_data& item) { - os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " << item.avg_price(); + os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " + << item.avg_price(); return os; } -Sales_data operator+(const Sales_data &lhs, const Sales_data &rhs) +Sales_data operator+(const Sales_data& lhs, const Sales_data& rhs) { Sales_data sum = lhs; sum += rhs; diff --git a/ch14/ex14_02.h b/ch14/ex14_02.h index a2dab9a0..e7320318 100644 --- a/ch14/ex14_02.h +++ b/ch14/ex14_02.h @@ -15,15 +15,19 @@ #include class Sales_data { - friend std::istream& operator>>(std::istream&, Sales_data&); // input + friend std::istream& operator>>(std::istream&, Sales_data&); // input friend std::ostream& operator<<(std::ostream&, const Sales_data&); // output - friend Sales_data operator+(const Sales_data&, const Sales_data&); // addition + friend Sales_data operator+(const Sales_data&, + const Sales_data&); // addition public: - Sales_data(const std::string &s, unsigned n, double p):bookNo(s),units_sold(n),revenue(n*p){} - Sales_data() : Sales_data("", 0, 0.0f){} - Sales_data(const std::string &s) : Sales_data(s, 0, 0.0f){} - Sales_data(std::istream &is); + Sales_data(const std::string& s, unsigned n, double p) + : bookNo(s), units_sold(n), revenue(n * p) + { + } + Sales_data() : Sales_data("", 0, 0.0f) {} + Sales_data(const std::string& s) : Sales_data(s, 0, 0.0f) {} + Sales_data(std::istream& is); Sales_data& operator+=(const Sales_data&); // compound-assignment std::string isbn() const { return bookNo; } @@ -42,7 +46,7 @@ Sales_data operator+(const Sales_data&, const Sales_data&); inline double Sales_data::avg_price() const { - return units_sold ? revenue/units_sold : 0; + return units_sold ? revenue / units_sold : 0; } #endif diff --git a/ch14/ex14_05.cpp b/ch14/ex14_05.cpp index b4759c6a..e9c7b4a4 100644 --- a/ch14/ex14_05.cpp +++ b/ch14/ex14_05.cpp @@ -1,23 +1,24 @@ #include "ex14_05.h" -std::istream& operator>>(std::istream &in, Book &book) +std::istream& operator>>(std::istream& in, Book& book) { in >> book.no_ >> book.name_ >> book.author_ >> book.pubdate_; return in; } -std::ostream& operator<<(std::ostream &out, const Book &book) +std::ostream& operator<<(std::ostream& out, const Book& book) { - out << book.no_ << " " << book.name_ << " " << book.author_ << " " << book.pubdate_; + out << book.no_ << " " << book.name_ << " " << book.author_ << " " + << book.pubdate_; return out; } -bool operator==(const Book &lhs, const Book &rhs) +bool operator==(const Book& lhs, const Book& rhs) { return lhs.no_ == rhs.no_; } -bool operator!=(const Book &lhs, const Book &rhs) +bool operator!=(const Book& lhs, const Book& rhs) { return !(lhs == rhs); } diff --git a/ch14/ex14_05.h b/ch14/ex14_05.h index d7a7503b..1098983d 100644 --- a/ch14/ex14_05.h +++ b/ch14/ex14_05.h @@ -12,8 +12,11 @@ class Book { public: Book() = default; - Book(unsigned no, std::string name, std::string author, std::string pubdate):no_(no), name_(name), author_(author), pubdate_(pubdate) { } - Book(std::istream &in) { in >> *this; } + Book(unsigned no, std::string name, std::string author, std::string pubdate) + : no_(no), name_(name), author_(author), pubdate_(pubdate) + { + } + Book(std::istream& in) { in >> *this; } private: unsigned no_; @@ -27,5 +30,4 @@ std::ostream& operator<<(std::ostream&, const Book&); bool operator==(const Book&, const Book&); bool operator!=(const Book&, const Book&); - #endif // BOOK_H diff --git a/ch14/ex14_05_TEST.cpp b/ch14/ex14_05_TEST.cpp index 62835bac..6078135d 100644 --- a/ch14/ex14_05_TEST.cpp +++ b/ch14/ex14_05_TEST.cpp @@ -5,6 +5,5 @@ int main() Book book1(123, "CP5", "Lippman", "2012"); Book book2(123, "CP5", "Lippman", "2012"); - if (book1 == book2) - std::cout << book1 << std::endl; + if (book1 == book2) std::cout << book1 << std::endl; } diff --git a/ch14/ex14_07.cpp b/ch14/ex14_07.cpp index 4665f775..7ad8d7c8 100644 --- a/ch14/ex14_07.cpp +++ b/ch14/ex14_07.cpp @@ -2,61 +2,58 @@ #include #include -std::pair -String::alloc_n_copy(const char *b, const char *e) +std::pair String::alloc_n_copy(const char* b, const char* e) { - auto str = alloc.allocate(e-b); - return{ str, std::uninitialized_copy(b, e, str)}; + auto str = alloc.allocate(e - b); + return {str, std::uninitialized_copy(b, e, str)}; } -void String::range_initializer(const char *first, const char *last) +void String::range_initializer(const char* first, const char* last) { - auto newstr = alloc_n_copy(first, last); - elements = newstr.first; - end = newstr.second; + auto newstr = alloc_n_copy(first, last); + elements = newstr.first; + end = newstr.second; } -String::String(const char *s) +String::String(const char* s) { - char *sl = const_cast(s); - while (*sl) - ++sl; - range_initializer(s, ++sl); + char* sl = const_cast(s); + while (*sl) ++sl; + range_initializer(s, ++sl); } String::String(const String& rhs) { - range_initializer(rhs.elements, rhs.end); + range_initializer(rhs.elements, rhs.end); std::cout << "copy constructor" << std::endl; } void String::free() { - if (elements) { - std::for_each(elements, end, [this](char &c){ alloc.destroy(&c); }); - alloc.deallocate(elements, end - elements); - } + if (elements) { + std::for_each(elements, end, [this](char& c) { alloc.destroy(&c); }); + alloc.deallocate(elements, end - elements); + } } String::~String() { - free(); + free(); } -String& String::operator = (const String &rhs) +String& String::operator=(const String& rhs) { - auto newstr = alloc_n_copy(rhs.elements, rhs.end); - free(); - elements = newstr.first; - end = newstr.second; + auto newstr = alloc_n_copy(rhs.elements, rhs.end); + free(); + elements = newstr.first; + end = newstr.second; std::cout << "copy-assignment" << std::endl; - return *this; + return *this; } -std::ostream& operator<<(std::ostream &os, const String &s) +std::ostream& operator<<(std::ostream& os, const String& s) { - char *c = const_cast(s.c_str()); - while (*c) - os << *c++; + char* c = const_cast(s.c_str()); + while (*c) os << *c++; return os; } diff --git a/ch14/ex14_07.h b/ch14/ex14_07.h index 343ec32e..33a837c6 100644 --- a/ch14/ex14_07.h +++ b/ch14/ex14_07.h @@ -4,32 +4,31 @@ #include #include -class String -{ +class String { friend std::ostream& operator<<(std::ostream&, const String&); + public: - String() : String("") {} - String(const char *); - String(const String&); - String& operator=(const String&); - ~String(); + String() : String("") {} + String(const char*); + String(const String&); + String& operator=(const String&); + ~String(); - const char *c_str() const { return elements; } - size_t size() const { return end - elements; } - size_t length() const { return end - elements - 1; } + const char* c_str() const { return elements; } + size_t size() const { return end - elements; } + size_t length() const { return end - elements - 1; } private: - std::pair alloc_n_copy(const char*, const char*); - void range_initializer(const char*, const char*); - void free(); + std::pair alloc_n_copy(const char*, const char*); + void range_initializer(const char*, const char*); + void free(); private: - char *elements; - char *end; - std::allocator alloc; + char* elements; + char* end; + std::allocator alloc; }; std::ostream& operator<<(std::ostream&, const String&); #endif - diff --git a/ch14/ex14_15.cpp b/ch14/ex14_15.cpp index d8823f36..4811cb8d 100644 --- a/ch14/ex14_15.cpp +++ b/ch14/ex14_15.cpp @@ -1,46 +1,47 @@ #include "ex14_15.h" -std::istream& operator>>(std::istream &in, Book &book) +std::istream& operator>>(std::istream& in, Book& book) { - in >> book.no_ >> book.name_ >> book.author_ >> book.pubdate_ >> book.number_; + in >> book.no_ >> book.name_ >> book.author_ >> book.pubdate_ >> + book.number_; return in; } -std::ostream& operator<<(std::ostream &out, const Book &book) +std::ostream& operator<<(std::ostream& out, const Book& book) { - out << book.no_ << " " << book.name_ << " " << book.author_ << " " << book.pubdate_ << " " << book.number_ << std::endl; + out << book.no_ << " " << book.name_ << " " << book.author_ << " " + << book.pubdate_ << " " << book.number_ << std::endl; return out; } -bool operator==(const Book &lhs, const Book &rhs) +bool operator==(const Book& lhs, const Book& rhs) { return lhs.no_ == rhs.no_; } -bool operator!=(const Book &lhs, const Book &rhs) +bool operator!=(const Book& lhs, const Book& rhs) { return !(lhs == rhs); } -bool operator<(const Book &lhs, const Book &rhs) +bool operator<(const Book& lhs, const Book& rhs) { return lhs.no_ < rhs.no_; } -bool operator>(const Book &lhs, const Book &rhs) +bool operator>(const Book& lhs, const Book& rhs) { return rhs < lhs; } -Book& Book::operator+=(const Book &rhs) +Book& Book::operator+=(const Book& rhs) { - if (rhs == *this) - this->number_ += rhs.number_; + if (rhs == *this) this->number_ += rhs.number_; return *this; } -Book operator+(const Book &lhs, const Book &rhs) +Book operator+(const Book& lhs, const Book& rhs) { Book book = lhs; book += rhs; diff --git a/ch14/ex14_15.h b/ch14/ex14_15.h index e26b7e07..23c46a41 100644 --- a/ch14/ex14_15.h +++ b/ch14/ex14_15.h @@ -15,8 +15,13 @@ class Book { public: Book() = default; - Book(unsigned no, std::string name, std::string author, std::string pubdate, unsigned number):no_(no), name_(name), author_(author), pubdate_(pubdate), number_(number) { } - Book(std::istream &in) { in >> *this; } + Book(unsigned no, std::string name, std::string author, std::string pubdate, + unsigned number) + : no_(no), name_(name), author_(author), pubdate_(pubdate), + number_(number) + { + } + Book(std::istream& in) { in >> *this; } Book& operator+=(const Book&); diff --git a/ch14/ex14_16_StrBlob.cpp b/ch14/ex14_16_StrBlob.cpp index ad5f286d..048836d7 100644 --- a/ch14/ex14_16_StrBlob.cpp +++ b/ch14/ex14_16_StrBlob.cpp @@ -6,34 +6,34 @@ // //================================================================== -bool operator==(const StrBlob &lhs, const StrBlob &rhs) +bool operator==(const StrBlob& lhs, const StrBlob& rhs) { - return *lhs.data == *rhs.data; + return *lhs.data == *rhs.data; } -bool operator!=(const StrBlob &lhs, const StrBlob &rhs) +bool operator!=(const StrBlob& lhs, const StrBlob& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator==(const StrBlobPtr &lhs, const StrBlobPtr &rhs) +bool operator==(const StrBlobPtr& lhs, const StrBlobPtr& rhs) { - return lhs.curr == rhs.curr; + return lhs.curr == rhs.curr; } -bool operator!=(const StrBlobPtr &lhs, const StrBlobPtr &rhs) +bool operator!=(const StrBlobPtr& lhs, const StrBlobPtr& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator==(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator==(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr == rhs.curr; + return lhs.curr == rhs.curr; } -bool operator!=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator!=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } //================================================================== @@ -42,20 +42,20 @@ bool operator!=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) // //================================================================== -StrBlob& StrBlob::operator=(const StrBlob &lhs) +StrBlob& StrBlob::operator=(const StrBlob& lhs) { - data = make_shared>(*lhs.data); - return *this; + data = make_shared>(*lhs.data); + return *this; } -StrBlob& StrBlob::operator=(StrBlob &&rhs) NOEXCEPT +StrBlob& StrBlob::operator=(StrBlob&& rhs) NOEXCEPT { - if (this != &rhs) { - data = std::move(rhs.data); - rhs.data = nullptr; - } + if (this != &rhs) { + data = std::move(rhs.data); + rhs.data = nullptr; + } - return *this; + return *this; } //================================================================== @@ -66,12 +66,12 @@ StrBlob& StrBlob::operator=(StrBlob &&rhs) NOEXCEPT StrBlobPtr StrBlob::begin() { - return StrBlobPtr(*this); + return StrBlobPtr(*this); } StrBlobPtr StrBlob::end() { - return StrBlobPtr(*this, data->size()); + return StrBlobPtr(*this, data->size()); } ConstStrBlobPtr StrBlob::cbegin() const diff --git a/ch14/ex14_16_StrBlob.h b/ch14/ex14_16_StrBlob.h index c0c6d11e..9278c1ac 100644 --- a/ch14/ex14_16_StrBlob.h +++ b/ch14/ex14_16_StrBlob.h @@ -24,7 +24,8 @@ using std::string; using std::initializer_list; #include -using std::make_shared; using std::shared_ptr; +using std::make_shared; +using std::shared_ptr; #include @@ -44,24 +45,26 @@ class ConstStrBlobPtr; //================================================================================= class StrBlob { - using size_type = vector::size_type; - friend class ConstStrBlobPtr; - friend class StrBlobPtr; - friend bool operator==(const StrBlob&, const StrBlob&); - friend bool operator!=(const StrBlob&, const StrBlob&); + using size_type = vector::size_type; + friend class ConstStrBlobPtr; + friend class StrBlobPtr; + friend bool operator==(const StrBlob&, const StrBlob&); + friend bool operator!=(const StrBlob&, const StrBlob&); public: - StrBlob() : data(make_shared>()) {} - StrBlob(initializer_list il) : data(make_shared>(il)) {} + StrBlob() : data(make_shared>()) {} + StrBlob(initializer_list il) : data(make_shared>(il)) + { + } - StrBlob(const StrBlob &sb) : data(make_shared>(*sb.data)) {} - StrBlob& operator=(const StrBlob&); + StrBlob(const StrBlob& sb) : data(make_shared>(*sb.data)) {} + StrBlob& operator=(const StrBlob&); - StrBlob(StrBlob &&rhs) NOEXCEPT : data(std::move(rhs.data)) {} - StrBlob& operator=(StrBlob &&) NOEXCEPT; + StrBlob(StrBlob&& rhs) NOEXCEPT : data(std::move(rhs.data)) {} + StrBlob& operator=(StrBlob&&) NOEXCEPT; - StrBlobPtr begin(); - StrBlobPtr end(); + StrBlobPtr begin(); + StrBlobPtr end(); ConstStrBlobPtr cbegin() const; ConstStrBlobPtr cend() const; @@ -69,17 +72,17 @@ class StrBlob { size_type size() const { return data->size(); } bool empty() const { return data->empty(); } - void push_back(const string &t) { data->push_back(t); } - void push_back(string &&s) { data->push_back(std::move(s)); } + void push_back(const string& t) { data->push_back(t); } + void push_back(string&& s) { data->push_back(std::move(s)); } - void pop_back(); - string& front(); - string& back(); - const string& front() const; - const string& back() const; + void pop_back(); + string& front(); + string& back(); + const string& front() const; + const string& back() const; private: - void check(size_type, const string&) const; + void check(size_type, const string&) const; shared_ptr> data; }; @@ -89,37 +92,37 @@ bool operator!=(const StrBlob&, const StrBlob&); inline void StrBlob::pop_back() { - check(0, "pop_back on empty StrBlob"); - data->pop_back(); + check(0, "pop_back on empty StrBlob"); + data->pop_back(); } inline string& StrBlob::front() { - check(0, "front on empty StrBlob"); - return data->front(); + check(0, "front on empty StrBlob"); + return data->front(); } inline string& StrBlob::back() { - check(0, "back on empty StrBlob"); - return data->back(); + check(0, "back on empty StrBlob"); + return data->back(); } inline const string& StrBlob::front() const { - check(0, "front on empty StrBlob"); - return data->front(); + check(0, "front on empty StrBlob"); + return data->front(); } inline const string& StrBlob::back() const { - check(0, "back on empty StrBlob"); - return data->back(); + check(0, "back on empty StrBlob"); + return data->back(); } -inline void StrBlob::check(size_type i, const string &msg) const +inline void StrBlob::check(size_type i, const string& msg) const { - if (i >= data->size()) throw std::out_of_range(msg); + if (i >= data->size()) throw std::out_of_range(msg); } //================================================================================= @@ -129,20 +132,21 @@ inline void StrBlob::check(size_type i, const string &msg) const //================================================================================= class StrBlobPtr { - friend bool operator==(const StrBlobPtr&, const StrBlobPtr&); - friend bool operator!=(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator==(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator!=(const StrBlobPtr&, const StrBlobPtr&); + public: - StrBlobPtr() : curr(0) {} - StrBlobPtr(StrBlob &s, size_t sz = 0) : wptr(s.data), curr(sz) {} + StrBlobPtr() : curr(0) {} + StrBlobPtr(StrBlob& s, size_t sz = 0) : wptr(s.data), curr(sz) {} - string& deref() const; - StrBlobPtr& incr(); + string& deref() const; + StrBlobPtr& incr(); private: - shared_ptr> check(size_t, const string&) const; + shared_ptr> check(size_t, const string&) const; - std::weak_ptr> wptr; - size_t curr; + std::weak_ptr> wptr; + size_t curr; }; bool operator==(const StrBlobPtr&, const StrBlobPtr&); @@ -150,23 +154,24 @@ bool operator!=(const StrBlobPtr&, const StrBlobPtr&); inline string& StrBlobPtr::deref() const { - auto p = check(curr, "dereference past end"); - return (*p)[curr]; + auto p = check(curr, "dereference past end"); + return (*p)[curr]; } inline StrBlobPtr& StrBlobPtr::incr() { - check(curr, "increment past end of StrBlobPtr"); - ++curr; - return *this; + check(curr, "increment past end of StrBlobPtr"); + ++curr; + return *this; } -inline shared_ptr> StrBlobPtr::check(size_t i, const string &msg) const +inline shared_ptr> StrBlobPtr::check(size_t i, + const string& msg) const { - auto ret = wptr.lock(); - if (!ret) throw std::runtime_error("unbound StrBlobPtr"); - if (i >= ret->size()) throw std::out_of_range(msg); - return ret; + auto ret = wptr.lock(); + if (!ret) throw std::runtime_error("unbound StrBlobPtr"); + if (i >= ret->size()) throw std::out_of_range(msg); + return ret; } //================================================================================= @@ -176,18 +181,18 @@ inline shared_ptr> StrBlobPtr::check(size_t i, const string &msg) //================================================================================= class ConstStrBlobPtr { - friend bool operator==(const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator!=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator==(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator!=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); public: - ConstStrBlobPtr() : curr(0) {} - ConstStrBlobPtr(const StrBlob &s, size_t sz = 0) : wptr(s.data), curr(sz) {} + ConstStrBlobPtr() : curr(0) {} + ConstStrBlobPtr(const StrBlob& s, size_t sz = 0) : wptr(s.data), curr(sz) {} - const string& deref() const; - ConstStrBlobPtr& incr(); + const string& deref() const; + ConstStrBlobPtr& incr(); private: - std::shared_ptr> check(size_t, const string&) const; + std::shared_ptr> check(size_t, const string&) const; std::weak_ptr> wptr; size_t curr; @@ -195,26 +200,27 @@ class ConstStrBlobPtr { inline const string& ConstStrBlobPtr::deref() const { - auto p = check(curr, "dereference past end"); - return (*p)[curr]; + auto p = check(curr, "dereference past end"); + return (*p)[curr]; } inline ConstStrBlobPtr& ConstStrBlobPtr::incr() { - check(curr, "increment past end of StrBlobPtr"); - ++curr; - return *this; + check(curr, "increment past end of StrBlobPtr"); + ++curr; + return *this; } -inline std::shared_ptr> ConstStrBlobPtr::check(size_t i, const string &msg) const +inline std::shared_ptr> +ConstStrBlobPtr::check(size_t i, const string& msg) const { - auto ret = wptr.lock(); - if (!ret) throw std::runtime_error("unbound StrBlobPtr"); - if (i >= ret->size()) throw std::out_of_range(msg); - return ret; + auto ret = wptr.lock(); + if (!ret) throw std::runtime_error("unbound StrBlobPtr"); + if (i >= ret->size()) throw std::out_of_range(msg); + return ret; } bool operator==(const ConstStrBlobPtr&, const ConstStrBlobPtr&); bool operator!=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); -#endif //CP5_STRBLOB_H_ +#endif // CP5_STRBLOB_H_ diff --git a/ch14/ex14_16_StrBlobTest.cpp b/ch14/ex14_16_StrBlobTest.cpp index e6d76f44..c3c6a191 100644 --- a/ch14/ex14_16_StrBlobTest.cpp +++ b/ch14/ex14_16_StrBlobTest.cpp @@ -3,10 +3,10 @@ int main() { - StrBlob sb{ "Hello", "World", "Pezy" }; + StrBlob sb{"Hello", "World", "Pezy"}; - for (ConstStrBlobPtr iter = sb.cbegin(); iter != sb.cend(); iter.incr()) { - std::cout << iter.deref() << " "; - } - std::cout << std::endl; + for (ConstStrBlobPtr iter = sb.cbegin(); iter != sb.cend(); iter.incr()) { + std::cout << iter.deref() << " "; + } + std::cout << std::endl; } diff --git a/ch14/ex14_16_StrVec.cpp b/ch14/ex14_16_StrVec.cpp index 93755dfe..bcc80886 100644 --- a/ch14/ex14_16_StrVec.cpp +++ b/ch14/ex14_16_StrVec.cpp @@ -1,125 +1,128 @@ #include "ex14_16_StrVec.h" #include // for_each, equal -void StrVec::push_back(const std::string &s) +void StrVec::push_back(const std::string& s) { - chk_n_alloc(); - alloc.construct(first_free++, s); + chk_n_alloc(); + alloc.construct(first_free++, s); } -std::pair -StrVec::alloc_n_copy(const std::string *b, const std::string *e) +std::pair StrVec::alloc_n_copy(const std::string* b, + const std::string* e) { - auto data = alloc.allocate(e-b); - return { data, std::uninitialized_copy(b, e, data) }; + auto data = alloc.allocate(e - b); + return {data, std::uninitialized_copy(b, e, data)}; } void StrVec::free() { - if (elements) { - for_each(elements, first_free, [this](std::string &rhs){ alloc.destroy(&rhs); }); - alloc.deallocate(elements, cap - elements); - } + if (elements) { + for_each(elements, first_free, + [this](std::string& rhs) { alloc.destroy(&rhs); }); + alloc.deallocate(elements, cap - elements); + } } -void StrVec::range_initialize(const std::string *first, const std::string *last) +void StrVec::range_initialize(const std::string* first, const std::string* last) { - auto newdata = alloc_n_copy(first, last); - elements = newdata.first; - first_free = cap = newdata.second; + auto newdata = alloc_n_copy(first, last); + elements = newdata.first; + first_free = cap = newdata.second; } -StrVec::StrVec(const StrVec &rhs) +StrVec::StrVec(const StrVec& rhs) { - range_initialize(rhs.begin(), rhs.end()); + range_initialize(rhs.begin(), rhs.end()); } StrVec::StrVec(std::initializer_list il) { - range_initialize(il.begin(), il.end()); + range_initialize(il.begin(), il.end()); } StrVec::~StrVec() { - free(); + free(); } -StrVec& StrVec::operator = (const StrVec &rhs) +StrVec& StrVec::operator=(const StrVec& rhs) { - auto data = alloc_n_copy(rhs.begin(), rhs.end()); - free(); - elements = data.first; - first_free = cap = data.second; - return *this; + auto data = alloc_n_copy(rhs.begin(), rhs.end()); + free(); + elements = data.first; + first_free = cap = data.second; + return *this; } void StrVec::alloc_n_move(size_t new_cap) { - auto newdata = alloc.allocate(new_cap); - auto dest = newdata; - auto elem = elements; - for (size_t i = 0; i != size(); ++i) - alloc.construct(dest++, std::move(*elem++)); - free(); - elements = newdata; - first_free = dest; - cap = elements + new_cap; + auto newdata = alloc.allocate(new_cap); + auto dest = newdata; + auto elem = elements; + for (size_t i = 0; i != size(); ++i) + alloc.construct(dest++, std::move(*elem++)); + free(); + elements = newdata; + first_free = dest; + cap = elements + new_cap; } void StrVec::reallocate() { - auto newcapacity = size() ? 2 * size() : 1; - alloc_n_move(newcapacity); + auto newcapacity = size() ? 2 * size() : 1; + alloc_n_move(newcapacity); } void StrVec::reserve(size_t new_cap) { - if (new_cap <= capacity()) return; - alloc_n_move(new_cap); + if (new_cap <= capacity()) return; + alloc_n_move(new_cap); } void StrVec::resize(size_t count) { - resize(count, std::string()); + resize(count, std::string()); } -void StrVec::resize(size_t count, const std::string &s) +void StrVec::resize(size_t count, const std::string& s) { - if (count > size()) { - if (count > capacity()) reserve(count * 2); - for (size_t i = size(); i != count; ++i) - alloc.construct(first_free++, s); - } - else if (count < size()) { - while (first_free != elements + count) - alloc.destroy(--first_free); - } + if (count > size()) { + if (count > capacity()) reserve(count * 2); + for (size_t i = size(); i != count; ++i) + alloc.construct(first_free++, s); + } + else if (count < size()) { + while (first_free != elements + count) alloc.destroy(--first_free); + } } -StrVec::StrVec(StrVec &&s) NOEXCEPT : elements(s.elements), first_free(s.first_free), cap(s.cap) +StrVec::StrVec(StrVec&& s) NOEXCEPT : elements(s.elements), + first_free(s.first_free), + cap(s.cap) { - // leave s in a state in which it is safe to run the destructor. - s.elements = s.first_free = s.cap = nullptr; + // leave s in a state in which it is safe to run the destructor. + s.elements = s.first_free = s.cap = nullptr; } -StrVec& StrVec::operator = (StrVec &&rhs) NOEXCEPT +StrVec& StrVec::operator=(StrVec&& rhs) NOEXCEPT { - if (this != &rhs) { - free(); - elements = rhs.elements; - first_free = rhs.first_free; - cap = rhs.cap; - rhs.elements = rhs.first_free = rhs.cap = nullptr; - } - return *this; + if (this != &rhs) { + free(); + elements = rhs.elements; + first_free = rhs.first_free; + cap = rhs.cap; + rhs.elements = rhs.first_free = rhs.cap = nullptr; + } + return *this; } -bool operator==(const StrVec &lhs, const StrVec &rhs) +bool operator==(const StrVec& lhs, const StrVec& rhs) { - return (lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin())); + return (lhs.size() == rhs.size() && + std::equal(lhs.begin(), lhs.end(), rhs.begin())); } -bool operator!=(const StrVec &lhs, const StrVec &rhs) +bool operator!=(const StrVec& lhs, const StrVec& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } diff --git a/ch14/ex14_16_StrVec.h b/ch14/ex14_16_StrVec.h index 6384c49a..78b2a395 100644 --- a/ch14/ex14_16_StrVec.h +++ b/ch14/ex14_16_StrVec.h @@ -11,50 +11,52 @@ #define NOEXCEPT #endif -class StrVec -{ - friend bool operator==(const StrVec&, const StrVec&); - friend bool operator!=(const StrVec&, const StrVec&); +class StrVec { + friend bool operator==(const StrVec&, const StrVec&); + friend bool operator!=(const StrVec&, const StrVec&); public: - StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} - StrVec(std::initializer_list); - StrVec(const StrVec&); - StrVec& operator=(const StrVec&); - StrVec(StrVec&&) NOEXCEPT; - StrVec& operator=(StrVec&&) NOEXCEPT; - ~StrVec(); - - void push_back(const std::string&); - size_t size() const { return first_free - elements; } - size_t capacity() const { return cap - elements; } - std::string *begin() const { return elements; } - std::string *end() const { return first_free; } - - std::string& at(size_t pos) { return *(elements + pos); } - const std::string& at(size_t pos) const { return *(elements + pos); } - - void reserve(size_t new_cap); - void resize(size_t count); - void resize(size_t count, const std::string&); + StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} + StrVec(std::initializer_list); + StrVec(const StrVec&); + StrVec& operator=(const StrVec&); + StrVec(StrVec&&) NOEXCEPT; + StrVec& operator=(StrVec&&) NOEXCEPT; + ~StrVec(); + + void push_back(const std::string&); + size_t size() const { return first_free - elements; } + size_t capacity() const { return cap - elements; } + std::string* begin() const { return elements; } + std::string* end() const { return first_free; } + + std::string& at(size_t pos) { return *(elements + pos); } + const std::string& at(size_t pos) const { return *(elements + pos); } + + void reserve(size_t new_cap); + void resize(size_t count); + void resize(size_t count, const std::string&); private: - std::pair alloc_n_copy(const std::string*, const std::string*); - void free(); - void chk_n_alloc() { if (size() == capacity()) reallocate(); } - void reallocate(); - void alloc_n_move(size_t new_cap); - void range_initialize(const std::string*, const std::string*); + std::pair alloc_n_copy(const std::string*, + const std::string*); + void free(); + void chk_n_alloc() + { + if (size() == capacity()) reallocate(); + } + void reallocate(); + void alloc_n_move(size_t new_cap); + void range_initialize(const std::string*, const std::string*); private: - std::string *elements; - std::string *first_free; - std::string *cap; - std::allocator alloc; + std::string* elements; + std::string* first_free; + std::string* cap; + std::allocator alloc; }; bool operator==(const StrVec&, const StrVec&); bool operator!=(const StrVec&, const StrVec&); #endif - diff --git a/ch14/ex14_16_StrVecMain.cpp b/ch14/ex14_16_StrVecMain.cpp index f26e893d..5af8047b 100644 --- a/ch14/ex14_16_StrVecMain.cpp +++ b/ch14/ex14_16_StrVecMain.cpp @@ -4,39 +4,38 @@ int main() { - StrVec vec; - vec.reserve(6); - std::cout << "capacity(reserve to 6): " << vec.capacity() << std::endl; + StrVec vec; + vec.reserve(6); + std::cout << "capacity(reserve to 6): " << vec.capacity() << std::endl; - vec.reserve(4); - std::cout << "capacity(reserve to 4): " << vec.capacity() << std::endl; + vec.reserve(4); + std::cout << "capacity(reserve to 4): " << vec.capacity() << std::endl; - vec.push_back("hello"); - vec.push_back("world"); + vec.push_back("hello"); + vec.push_back("world"); - vec.resize(4); + vec.resize(4); - for (auto i = vec.begin(); i != vec.end(); ++i) - std::cout << *i << std::endl; - std::cout << "-EOF-" << std::endl; + for (auto i = vec.begin(); i != vec.end(); ++i) + std::cout << *i << std::endl; + std::cout << "-EOF-" << std::endl; - vec.resize(1); + vec.resize(1); - for (auto i = vec.begin(); i != vec.end(); ++i) - std::cout << *i << std::endl; - std::cout << "-EOF-" << std::endl; + for (auto i = vec.begin(); i != vec.end(); ++i) + std::cout << *i << std::endl; + std::cout << "-EOF-" << std::endl; - StrVec vec_list{"hello", "world", "pezy"}; + StrVec vec_list{"hello", "world", "pezy"}; - for (auto i = vec_list.begin(); i != vec_list.end(); ++i) - std::cout << *i << " "; - std::cout << std::endl; + for (auto i = vec_list.begin(); i != vec_list.end(); ++i) + std::cout << *i << " "; + std::cout << std::endl; - // Test operator== + // Test operator== - const StrVec const_vec_list{ "hello", "world", "pezy" }; - if (vec_list == const_vec_list) - for (const auto &str : const_vec_list) - std::cout << str << " "; - std::cout << std::endl; + const StrVec const_vec_list{"hello", "world", "pezy"}; + if (vec_list == const_vec_list) + for (const auto& str : const_vec_list) std::cout << str << " "; + std::cout << std::endl; } diff --git a/ch14/ex14_16_String.cpp b/ch14/ex14_16_String.cpp index 73af4015..0debaf40 100644 --- a/ch14/ex14_16_String.cpp +++ b/ch14/ex14_16_String.cpp @@ -7,28 +7,29 @@ // //=========================================================================== -std::ostream& operator<<(std::ostream &os, const String &lhs) +std::ostream& operator<<(std::ostream& os, const String& lhs) { - os << lhs.c_str(); - return os; + os << lhs.c_str(); + return os; } -std::istream& operator>>(std::istream &is, String &rhs) +std::istream& operator>>(std::istream& is, String& rhs) { - for (char c; (c = is.get()) != '\n'; ) { - rhs.push_back(c); - } - return is; + for (char c; (c = is.get()) != '\n';) { + rhs.push_back(c); + } + return is; } -bool operator==(const String &lhs, const String &rhs) +bool operator==(const String& lhs, const String& rhs) { - return (lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin())); + return (lhs.size() == rhs.size() && + std::equal(lhs.begin(), lhs.end(), rhs.begin())); } -bool operator!=(const String &lhs, const String &rhs) +bool operator!=(const String& lhs, const String& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } //=========================================================================== @@ -37,12 +38,11 @@ bool operator!=(const String &lhs, const String &rhs) // //=========================================================================== -String::String(const char *s) +String::String(const char* s) { - char *sl = const_cast(s); - while (*sl) - ++sl; - range_initializer(s, ++sl); + char* sl = const_cast(s); + while (*sl) ++sl; + range_initializer(s, ++sl); } //=========================================================================== @@ -53,40 +53,43 @@ String::String(const char *s) String::String(const String& rhs) { - range_initializer(rhs.elements, rhs.first_free); + range_initializer(rhs.elements, rhs.first_free); } -String& String::operator = (const String &rhs) +String& String::operator=(const String& rhs) { - auto newstr = alloc_n_copy(rhs.elements, rhs.first_free); - free(); - elements = newstr.first; - first_free = cap = newstr.second; - last_elem = first_free - 1; - return *this; + auto newstr = alloc_n_copy(rhs.elements, rhs.first_free); + free(); + elements = newstr.first; + first_free = cap = newstr.second; + last_elem = first_free - 1; + return *this; } -String::String(String &&s) NOEXCEPT : elements(s.elements), last_elem(s.last_elem), first_free(s.first_free), cap(s.cap) +String::String(String&& s) NOEXCEPT : elements(s.elements), + last_elem(s.last_elem), + first_free(s.first_free), + cap(s.cap) { - s.elements = s.last_elem = s.first_free = s.cap = nullptr; + s.elements = s.last_elem = s.first_free = s.cap = nullptr; } -String& String::operator = (String &&rhs) NOEXCEPT +String& String::operator=(String&& rhs) NOEXCEPT { - if (this != &rhs) { - free(); - elements = rhs.elements; - last_elem = rhs.last_elem; - first_free = rhs.first_free; - cap = rhs.cap; - rhs.elements = rhs.last_elem = rhs.first_free = rhs.cap = nullptr; - } - return *this; + if (this != &rhs) { + free(); + elements = rhs.elements; + last_elem = rhs.last_elem; + first_free = rhs.first_free; + cap = rhs.cap; + rhs.elements = rhs.last_elem = rhs.first_free = rhs.cap = nullptr; + } + return *this; } String::~String() { - free(); + free(); } //=========================================================================== @@ -97,86 +100,85 @@ String::~String() void String::push_back(const char c) { - chk_n_alloc(); - *last_elem = c; - last_elem = first_free; - alloc.construct(first_free++, '\0'); + chk_n_alloc(); + *last_elem = c; + last_elem = first_free; + alloc.construct(first_free++, '\0'); } void String::reallocate() { - // \0 | - - // ^ ^ - // elements first_free - // last_elem cap + // \0 | - + // ^ ^ + // elements first_free + // last_elem cap - auto newcapacity = size() ? 2 * (size() + 1) : 2; - alloc_n_move(newcapacity); + auto newcapacity = size() ? 2 * (size() + 1) : 2; + alloc_n_move(newcapacity); } void String::alloc_n_move(size_t new_cap) { - auto newdata = alloc.allocate(new_cap); - auto dest = newdata; - auto elem = elements; - for (size_t i = 0; i != size() + 1; ++i) - alloc.construct(dest++, std::move(*elem++)); - free(); - elements = newdata; - last_elem = dest - 1; - first_free = dest; - cap = elements + new_cap; + auto newdata = alloc.allocate(new_cap); + auto dest = newdata; + auto elem = elements; + for (size_t i = 0; i != size() + 1; ++i) + alloc.construct(dest++, std::move(*elem++)); + free(); + elements = newdata; + last_elem = dest - 1; + first_free = dest; + cap = elements + new_cap; } void String::free() { - if (elements) { - std::for_each(elements, first_free, [this](char &c){ alloc.destroy(&c); }); - alloc.deallocate(elements, cap - elements); - } + if (elements) { + std::for_each(elements, first_free, + [this](char& c) { alloc.destroy(&c); }); + alloc.deallocate(elements, cap - elements); + } } -std::pair -String::alloc_n_copy(const char *b, const char *e) +std::pair String::alloc_n_copy(const char* b, const char* e) { - auto str = alloc.allocate(e-b); - return{ str, std::uninitialized_copy(b, e, str)}; + auto str = alloc.allocate(e - b); + return {str, std::uninitialized_copy(b, e, str)}; } -void String::range_initializer(const char *first, const char *last) +void String::range_initializer(const char* first, const char* last) { - auto newstr = alloc_n_copy(first, last); - elements = newstr.first; - first_free = cap = newstr.second; - last_elem = first_free - 1; + auto newstr = alloc_n_copy(first, last); + elements = newstr.first; + first_free = cap = newstr.second; + last_elem = first_free - 1; } void String::reserve(size_t new_cap) { - if (new_cap <= capacity()) return; - alloc_n_move(new_cap); + if (new_cap <= capacity()) return; + alloc_n_move(new_cap); } void String::resize(size_t count, char c) { - if (count > size()) { - if (count > capacity()) reserve(count * 2); - for (size_t i = size(); i != count; ++i) { - *last_elem++ = c; - alloc.construct(first_free++, '\0'); - } - - } - else if (count < size()) { - while (last_elem != elements + count) { - --last_elem; - alloc.destroy(--first_free); - } - *last_elem = '\0'; - } + if (count > size()) { + if (count > capacity()) reserve(count * 2); + for (size_t i = size(); i != count; ++i) { + *last_elem++ = c; + alloc.construct(first_free++, '\0'); + } + } + else if (count < size()) { + while (last_elem != elements + count) { + --last_elem; + alloc.destroy(--first_free); + } + *last_elem = '\0'; + } } void String::resize(size_t count) { - resize(count, ' '); + resize(count, ' '); } diff --git a/ch14/ex14_16_String.h b/ch14/ex14_16_String.h index b4e71eb1..f8b29c21 100644 --- a/ch14/ex14_16_String.h +++ b/ch14/ex14_16_String.h @@ -18,50 +18,52 @@ // //=================================================================================== -class String -{ - friend std::ostream& operator<<(std::ostream&, const String&); - friend std::istream& operator>>(std::istream&, String&); - friend bool operator==(const String&, const String&); - friend bool operator!=(const String&, const String&); +class String { + friend std::ostream& operator<<(std::ostream&, const String&); + friend std::istream& operator>>(std::istream&, String&); + friend bool operator==(const String&, const String&); + friend bool operator!=(const String&, const String&); public: - String() : String("") {} - String(const char *); - String(const String&); - String& operator=(const String&); - String(String &&) NOEXCEPT; - String& operator=(String&&) NOEXCEPT; - ~String(); + String() : String("") {} + String(const char*); + String(const String&); + String& operator=(const String&); + String(String&&) NOEXCEPT; + String& operator=(String&&) NOEXCEPT; + ~String(); - void push_back(const char); + void push_back(const char); - char* begin() const { return elements; } - char* end() const { return last_elem; } + char* begin() const { return elements; } + char* end() const { return last_elem; } - const char *c_str() const { return elements; } - size_t size() const { return last_elem - elements; } - size_t length() const { return size(); } - size_t capacity() const { return cap - elements; } + const char* c_str() const { return elements; } + size_t size() const { return last_elem - elements; } + size_t length() const { return size(); } + size_t capacity() const { return cap - elements; } - void reserve(size_t); - void resize(size_t); - void resize(size_t, char); + void reserve(size_t); + void resize(size_t); + void resize(size_t, char); private: - std::pair alloc_n_copy(const char*, const char*); - void range_initializer(const char*, const char*); - void free(); - void reallocate(); - void alloc_n_move(size_t new_cap); - void chk_n_alloc() { if (first_free == cap) reallocate(); } + std::pair alloc_n_copy(const char*, const char*); + void range_initializer(const char*, const char*); + void free(); + void reallocate(); + void alloc_n_move(size_t new_cap); + void chk_n_alloc() + { + if (first_free == cap) reallocate(); + } private: - char *elements; - char *last_elem; - char *first_free; - char *cap; - std::allocator alloc; + char* elements; + char* last_elem; + char* first_free; + char* cap; + std::allocator alloc; }; std::ostream& operator<<(std::ostream&, const String&); @@ -70,4 +72,3 @@ bool operator==(const String&, const String&); bool operator!=(const String&, const String&); #endif - diff --git a/ch14/ex14_16_StringMain.cpp b/ch14/ex14_16_StringMain.cpp index 253dd593..950073f1 100644 --- a/ch14/ex14_16_StringMain.cpp +++ b/ch14/ex14_16_StringMain.cpp @@ -7,55 +7,54 @@ void foo(String x) { - std::cout << x << std::endl; + std::cout << x << std::endl; } void bar(const String& x) { - std::cout << x.c_str() << std::endl; + std::cout << x.c_str() << std::endl; } String baz() { - String ret("world"); - return ret; + String ret("world"); + return ret; } int main() { - char text[] = "world"; - - String s0; - String s1("hello"); - String s2(std::move(s0)); - String s3 = s1; - String s4(text); - s2 = s1; - - if (s2 == s1) - std::cout << "s2 == s1" << std::endl; - - foo(s1); - bar(s1); - foo("temporary"); - bar("temporary"); - String s5 = baz(); - - std::vector svec; - //svec.push_back(s0); - svec.push_back(s1); - svec.push_back(s2); - svec.push_back(s3); - svec.push_back(s4); - svec.push_back(baz()); - svec.push_back("good job"); - - for (const auto &s : svec) { - std::cout << s << std::endl; - } - - std::cout << "Input a string: "; - String s6; - std::cin >> s6; - std::cout << s6 << std::endl; + char text[] = "world"; + + String s0; + String s1("hello"); + String s2(std::move(s0)); + String s3 = s1; + String s4(text); + s2 = s1; + + if (s2 == s1) std::cout << "s2 == s1" << std::endl; + + foo(s1); + bar(s1); + foo("temporary"); + bar("temporary"); + String s5 = baz(); + + std::vector svec; + // svec.push_back(s0); + svec.push_back(s1); + svec.push_back(s2); + svec.push_back(s3); + svec.push_back(s4); + svec.push_back(baz()); + svec.push_back("good job"); + + for (const auto& s : svec) { + std::cout << s << std::endl; + } + + std::cout << "Input a string: "; + String s6; + std::cin >> s6; + std::cout << s6 << std::endl; } diff --git a/ch14/ex14_18_StrBlob.cpp b/ch14/ex14_18_StrBlob.cpp index 2ea24ede..d4dd967d 100644 --- a/ch14/ex14_18_StrBlob.cpp +++ b/ch14/ex14_18_StrBlob.cpp @@ -7,34 +7,35 @@ // //================================================================== -bool operator==(const StrBlob &lhs, const StrBlob &rhs) +bool operator==(const StrBlob& lhs, const StrBlob& rhs) { - return *lhs.data == *rhs.data; + return *lhs.data == *rhs.data; } -bool operator!=(const StrBlob &lhs, const StrBlob &rhs) +bool operator!=(const StrBlob& lhs, const StrBlob& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator< (const StrBlob &lhs, const StrBlob &rhs) +bool operator<(const StrBlob& lhs, const StrBlob& rhs) { - return std::lexicographical_compare(lhs.data->begin(), lhs.data->end(), rhs.data->begin(), rhs.data->end()); + return std::lexicographical_compare(lhs.data->begin(), lhs.data->end(), + rhs.data->begin(), rhs.data->end()); } -bool operator> (const StrBlob &lhs, const StrBlob &rhs) +bool operator>(const StrBlob& lhs, const StrBlob& rhs) { - return rhs < lhs; + return rhs < lhs; } -bool operator<=(const StrBlob &lhs, const StrBlob &rhs) +bool operator<=(const StrBlob& lhs, const StrBlob& rhs) { - return !(rhs < lhs); + return !(rhs < lhs); } -bool operator>=(const StrBlob &lhs, const StrBlob &rhs) +bool operator>=(const StrBlob& lhs, const StrBlob& rhs) { - return !(lhs < rhs); + return !(lhs < rhs); } //================================================================ @@ -43,34 +44,34 @@ bool operator>=(const StrBlob &lhs, const StrBlob &rhs) // //================================================================ -bool operator==(const StrBlobPtr &lhs, const StrBlobPtr &rhs) +bool operator==(const StrBlobPtr& lhs, const StrBlobPtr& rhs) { - return lhs.curr == rhs.curr; + return lhs.curr == rhs.curr; } -bool operator!=(const StrBlobPtr &lhs, const StrBlobPtr &rhs) +bool operator!=(const StrBlobPtr& lhs, const StrBlobPtr& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator< (const StrBlobPtr &x, const StrBlobPtr &y) +bool operator<(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr < y.curr; + return x.curr < y.curr; } -bool operator> (const StrBlobPtr &x, const StrBlobPtr &y) +bool operator>(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr > y.curr; + return x.curr > y.curr; } -bool operator<=(const StrBlobPtr &x, const StrBlobPtr &y) +bool operator<=(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr <= y.curr; + return x.curr <= y.curr; } -bool operator>=(const StrBlobPtr &x, const StrBlobPtr &y) +bool operator>=(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr >= y.curr; + return x.curr >= y.curr; } //================================================================ @@ -79,34 +80,34 @@ bool operator>=(const StrBlobPtr &x, const StrBlobPtr &y) // //================================================================ -bool operator==(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator==(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr == rhs.curr; + return lhs.curr == rhs.curr; } -bool operator!=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator!=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator< (const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator<(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr < rhs.curr; + return lhs.curr < rhs.curr; } -bool operator> (const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator>(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr > rhs.curr; + return lhs.curr > rhs.curr; } -bool operator<=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator<=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr <= rhs.curr; + return lhs.curr <= rhs.curr; } -bool operator>=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator>=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr >= rhs.curr; + return lhs.curr >= rhs.curr; } //================================================================== @@ -115,20 +116,20 @@ bool operator>=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) // //================================================================== -StrBlob& StrBlob::operator=(const StrBlob &lhs) +StrBlob& StrBlob::operator=(const StrBlob& lhs) { - data = make_shared>(*lhs.data); - return *this; + data = make_shared>(*lhs.data); + return *this; } -StrBlob& StrBlob::operator=(StrBlob &&rhs) NOEXCEPT +StrBlob& StrBlob::operator=(StrBlob&& rhs) NOEXCEPT { - if (this != &rhs) { - data = std::move(rhs.data); - rhs.data = nullptr; - } + if (this != &rhs) { + data = std::move(rhs.data); + rhs.data = nullptr; + } - return *this; + return *this; } //================================================================== @@ -139,12 +140,12 @@ StrBlob& StrBlob::operator=(StrBlob &&rhs) NOEXCEPT StrBlobPtr StrBlob::begin() { - return StrBlobPtr(*this); + return StrBlobPtr(*this); } StrBlobPtr StrBlob::end() { - return StrBlobPtr(*this, data->size()); + return StrBlobPtr(*this, data->size()); } ConstStrBlobPtr StrBlob::cbegin() const diff --git a/ch14/ex14_18_StrBlob.h b/ch14/ex14_18_StrBlob.h index 8de92257..4752a65a 100644 --- a/ch14/ex14_18_StrBlob.h +++ b/ch14/ex14_18_StrBlob.h @@ -24,7 +24,8 @@ using std::string; using std::initializer_list; #include -using std::make_shared; using std::shared_ptr; +using std::make_shared; +using std::shared_ptr; #include @@ -44,28 +45,30 @@ class ConstStrBlobPtr; //================================================================================= class StrBlob { - using size_type = vector::size_type; - friend class ConstStrBlobPtr; - friend class StrBlobPtr; - friend bool operator==(const StrBlob&, const StrBlob&); - friend bool operator!=(const StrBlob&, const StrBlob&); - friend bool operator< (const StrBlob&, const StrBlob&); - friend bool operator> (const StrBlob&, const StrBlob&); - friend bool operator<=(const StrBlob&, const StrBlob&); - friend bool operator>=(const StrBlob&, const StrBlob&); + using size_type = vector::size_type; + friend class ConstStrBlobPtr; + friend class StrBlobPtr; + friend bool operator==(const StrBlob&, const StrBlob&); + friend bool operator!=(const StrBlob&, const StrBlob&); + friend bool operator<(const StrBlob&, const StrBlob&); + friend bool operator>(const StrBlob&, const StrBlob&); + friend bool operator<=(const StrBlob&, const StrBlob&); + friend bool operator>=(const StrBlob&, const StrBlob&); public: - StrBlob() : data(make_shared>()) {} - StrBlob(initializer_list il) : data(make_shared>(il)) {} + StrBlob() : data(make_shared>()) {} + StrBlob(initializer_list il) : data(make_shared>(il)) + { + } - StrBlob(const StrBlob &sb) : data(make_shared>(*sb.data)) {} - StrBlob& operator=(const StrBlob&); + StrBlob(const StrBlob& sb) : data(make_shared>(*sb.data)) {} + StrBlob& operator=(const StrBlob&); - StrBlob(StrBlob &&rhs) NOEXCEPT : data(std::move(rhs.data)) {} - StrBlob& operator=(StrBlob &&) NOEXCEPT; + StrBlob(StrBlob&& rhs) NOEXCEPT : data(std::move(rhs.data)) {} + StrBlob& operator=(StrBlob&&) NOEXCEPT; - StrBlobPtr begin(); - StrBlobPtr end(); + StrBlobPtr begin(); + StrBlobPtr end(); ConstStrBlobPtr cbegin() const; ConstStrBlobPtr cend() const; @@ -73,61 +76,61 @@ class StrBlob { size_type size() const { return data->size(); } bool empty() const { return data->empty(); } - void push_back(const string &t) { data->push_back(t); } - void push_back(string &&s) { data->push_back(std::move(s)); } + void push_back(const string& t) { data->push_back(t); } + void push_back(string&& s) { data->push_back(std::move(s)); } - void pop_back(); - string& front(); - string& back(); - const string& front() const; - const string& back() const; + void pop_back(); + string& front(); + string& back(); + const string& front() const; + const string& back() const; private: - void check(size_type, const string&) const; + void check(size_type, const string&) const; shared_ptr> data; }; bool operator==(const StrBlob&, const StrBlob&); bool operator!=(const StrBlob&, const StrBlob&); -bool operator< (const StrBlob&, const StrBlob&); -bool operator> (const StrBlob&, const StrBlob&); +bool operator<(const StrBlob&, const StrBlob&); +bool operator>(const StrBlob&, const StrBlob&); bool operator<=(const StrBlob&, const StrBlob&); bool operator>=(const StrBlob&, const StrBlob&); inline void StrBlob::pop_back() { - check(0, "pop_back on empty StrBlob"); - data->pop_back(); + check(0, "pop_back on empty StrBlob"); + data->pop_back(); } inline string& StrBlob::front() { - check(0, "front on empty StrBlob"); - return data->front(); + check(0, "front on empty StrBlob"); + return data->front(); } inline string& StrBlob::back() { - check(0, "back on empty StrBlob"); - return data->back(); + check(0, "back on empty StrBlob"); + return data->back(); } inline const string& StrBlob::front() const { - check(0, "front on empty StrBlob"); - return data->front(); + check(0, "front on empty StrBlob"); + return data->front(); } inline const string& StrBlob::back() const { - check(0, "back on empty StrBlob"); - return data->back(); + check(0, "back on empty StrBlob"); + return data->back(); } -inline void StrBlob::check(size_type i, const string &msg) const +inline void StrBlob::check(size_type i, const string& msg) const { - if (i >= data->size()) throw std::out_of_range(msg); + if (i >= data->size()) throw std::out_of_range(msg); } //================================================================================= @@ -137,53 +140,54 @@ inline void StrBlob::check(size_type i, const string &msg) const //================================================================================= class StrBlobPtr { - friend bool operator==(const StrBlobPtr&, const StrBlobPtr&); - friend bool operator!=(const StrBlobPtr&, const StrBlobPtr&); - friend bool operator< (const StrBlobPtr&, const StrBlobPtr&); - friend bool operator> (const StrBlobPtr&, const StrBlobPtr&); - friend bool operator<=(const StrBlobPtr&, const StrBlobPtr&); - friend bool operator>=(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator==(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator!=(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator<(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator>(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator<=(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator>=(const StrBlobPtr&, const StrBlobPtr&); public: - StrBlobPtr() : curr(0) {} - StrBlobPtr(StrBlob &s, size_t sz = 0) : wptr(s.data), curr(sz) {} + StrBlobPtr() : curr(0) {} + StrBlobPtr(StrBlob& s, size_t sz = 0) : wptr(s.data), curr(sz) {} - string& deref() const; - StrBlobPtr& incr(); + string& deref() const; + StrBlobPtr& incr(); private: - shared_ptr> check(size_t, const string&) const; + shared_ptr> check(size_t, const string&) const; - std::weak_ptr> wptr; - size_t curr; + std::weak_ptr> wptr; + size_t curr; }; bool operator==(const StrBlobPtr&, const StrBlobPtr&); bool operator!=(const StrBlobPtr&, const StrBlobPtr&); -bool operator< (const StrBlobPtr&, const StrBlobPtr&); -bool operator> (const StrBlobPtr&, const StrBlobPtr&); +bool operator<(const StrBlobPtr&, const StrBlobPtr&); +bool operator>(const StrBlobPtr&, const StrBlobPtr&); bool operator<=(const StrBlobPtr&, const StrBlobPtr&); bool operator>=(const StrBlobPtr&, const StrBlobPtr&); inline string& StrBlobPtr::deref() const { - auto p = check(curr, "dereference past end"); - return (*p)[curr]; + auto p = check(curr, "dereference past end"); + return (*p)[curr]; } inline StrBlobPtr& StrBlobPtr::incr() { - check(curr, "increment past end of StrBlobPtr"); - ++curr; - return *this; + check(curr, "increment past end of StrBlobPtr"); + ++curr; + return *this; } -inline shared_ptr> StrBlobPtr::check(size_t i, const string &msg) const +inline shared_ptr> StrBlobPtr::check(size_t i, + const string& msg) const { - auto ret = wptr.lock(); - if (!ret) throw std::runtime_error("unbound StrBlobPtr"); - if (i >= ret->size()) throw std::out_of_range(msg); - return ret; + auto ret = wptr.lock(); + if (!ret) throw std::runtime_error("unbound StrBlobPtr"); + if (i >= ret->size()) throw std::out_of_range(msg); + return ret; } //================================================================================= @@ -193,22 +197,22 @@ inline shared_ptr> StrBlobPtr::check(size_t i, const string &msg) //================================================================================= class ConstStrBlobPtr { - friend bool operator==(const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator!=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator< (const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator> (const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator<=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator>=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator==(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator!=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator<(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator>(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator<=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator>=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); public: - ConstStrBlobPtr() : curr(0) {} - ConstStrBlobPtr(const StrBlob &s, size_t sz = 0) : wptr(s.data), curr(sz) {} + ConstStrBlobPtr() : curr(0) {} + ConstStrBlobPtr(const StrBlob& s, size_t sz = 0) : wptr(s.data), curr(sz) {} - const string& deref() const; - ConstStrBlobPtr& incr(); + const string& deref() const; + ConstStrBlobPtr& incr(); private: - std::shared_ptr> check(size_t, const string&) const; + std::shared_ptr> check(size_t, const string&) const; std::weak_ptr> wptr; size_t curr; @@ -216,30 +220,31 @@ class ConstStrBlobPtr { bool operator==(const ConstStrBlobPtr&, const ConstStrBlobPtr&); bool operator!=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); -bool operator< (const ConstStrBlobPtr&, const ConstStrBlobPtr&); -bool operator> (const ConstStrBlobPtr&, const ConstStrBlobPtr&); +bool operator<(const ConstStrBlobPtr&, const ConstStrBlobPtr&); +bool operator>(const ConstStrBlobPtr&, const ConstStrBlobPtr&); bool operator<=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); bool operator>=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); inline const string& ConstStrBlobPtr::deref() const { - auto p = check(curr, "dereference past end"); - return (*p)[curr]; + auto p = check(curr, "dereference past end"); + return (*p)[curr]; } inline ConstStrBlobPtr& ConstStrBlobPtr::incr() { - check(curr, "increment past end of StrBlobPtr"); - ++curr; - return *this; + check(curr, "increment past end of StrBlobPtr"); + ++curr; + return *this; } -inline std::shared_ptr> ConstStrBlobPtr::check(size_t i, const string &msg) const +inline std::shared_ptr> +ConstStrBlobPtr::check(size_t i, const string& msg) const { - auto ret = wptr.lock(); - if (!ret) throw std::runtime_error("unbound StrBlobPtr"); - if (i >= ret->size()) throw std::out_of_range(msg); - return ret; + auto ret = wptr.lock(); + if (!ret) throw std::runtime_error("unbound StrBlobPtr"); + if (i >= ret->size()) throw std::out_of_range(msg); + return ret; } -#endif //CP5_STRBLOB_H_ +#endif // CP5_STRBLOB_H_ diff --git a/ch14/ex14_18_StrBlobTest.cpp b/ch14/ex14_18_StrBlobTest.cpp index ad82c7c4..4740c8d3 100644 --- a/ch14/ex14_18_StrBlobTest.cpp +++ b/ch14/ex14_18_StrBlobTest.cpp @@ -3,12 +3,13 @@ int main() { - StrBlob sb1{ "a", "b", "c" }; - StrBlob sb2{ "a", "b", "b" }; + StrBlob sb1{"a", "b", "c"}; + StrBlob sb2{"a", "b", "b"}; - if (sb1 > sb2) { - for (ConstStrBlobPtr iter = sb1.cbegin(); iter < sb1.cend(); iter.incr()) - std::cout << iter.deref() << " "; - std::cout << std::endl; - } + if (sb1 > sb2) { + for (ConstStrBlobPtr iter = sb1.cbegin(); iter < sb1.cend(); + iter.incr()) + std::cout << iter.deref() << " "; + std::cout << std::endl; + } } diff --git a/ch14/ex14_18_StrVec.cpp b/ch14/ex14_18_StrVec.cpp index 9af95073..27552e6c 100644 --- a/ch14/ex14_18_StrVec.cpp +++ b/ch14/ex14_18_StrVec.cpp @@ -1,145 +1,149 @@ #include "ex14_18_StrVec.h" #include // for_each, equal -void StrVec::push_back(const std::string &s) +void StrVec::push_back(const std::string& s) { - chk_n_alloc(); - alloc.construct(first_free++, s); + chk_n_alloc(); + alloc.construct(first_free++, s); } -std::pair -StrVec::alloc_n_copy(const std::string *b, const std::string *e) +std::pair StrVec::alloc_n_copy(const std::string* b, + const std::string* e) { - auto data = alloc.allocate(e-b); - return { data, std::uninitialized_copy(b, e, data) }; + auto data = alloc.allocate(e - b); + return {data, std::uninitialized_copy(b, e, data)}; } void StrVec::free() { - if (elements) { - for_each(elements, first_free, [this](std::string &rhs){ alloc.destroy(&rhs); }); - alloc.deallocate(elements, cap - elements); - } + if (elements) { + for_each(elements, first_free, + [this](std::string& rhs) { alloc.destroy(&rhs); }); + alloc.deallocate(elements, cap - elements); + } } -void StrVec::range_initialize(const std::string *first, const std::string *last) +void StrVec::range_initialize(const std::string* first, const std::string* last) { - auto newdata = alloc_n_copy(first, last); - elements = newdata.first; - first_free = cap = newdata.second; + auto newdata = alloc_n_copy(first, last); + elements = newdata.first; + first_free = cap = newdata.second; } -StrVec::StrVec(const StrVec &rhs) +StrVec::StrVec(const StrVec& rhs) { - range_initialize(rhs.begin(), rhs.end()); + range_initialize(rhs.begin(), rhs.end()); } StrVec::StrVec(std::initializer_list il) { - range_initialize(il.begin(), il.end()); + range_initialize(il.begin(), il.end()); } StrVec::~StrVec() { - free(); + free(); } -StrVec& StrVec::operator = (const StrVec &rhs) +StrVec& StrVec::operator=(const StrVec& rhs) { - auto data = alloc_n_copy(rhs.begin(), rhs.end()); - free(); - elements = data.first; - first_free = cap = data.second; - return *this; + auto data = alloc_n_copy(rhs.begin(), rhs.end()); + free(); + elements = data.first; + first_free = cap = data.second; + return *this; } void StrVec::alloc_n_move(size_t new_cap) { - auto newdata = alloc.allocate(new_cap); - auto dest = newdata; - auto elem = elements; - for (size_t i = 0; i != size(); ++i) - alloc.construct(dest++, std::move(*elem++)); - free(); - elements = newdata; - first_free = dest; - cap = elements + new_cap; + auto newdata = alloc.allocate(new_cap); + auto dest = newdata; + auto elem = elements; + for (size_t i = 0; i != size(); ++i) + alloc.construct(dest++, std::move(*elem++)); + free(); + elements = newdata; + first_free = dest; + cap = elements + new_cap; } void StrVec::reallocate() { - auto newcapacity = size() ? 2 * size() : 1; - alloc_n_move(newcapacity); + auto newcapacity = size() ? 2 * size() : 1; + alloc_n_move(newcapacity); } void StrVec::reserve(size_t new_cap) { - if (new_cap <= capacity()) return; - alloc_n_move(new_cap); + if (new_cap <= capacity()) return; + alloc_n_move(new_cap); } void StrVec::resize(size_t count) { - resize(count, std::string()); + resize(count, std::string()); } -void StrVec::resize(size_t count, const std::string &s) +void StrVec::resize(size_t count, const std::string& s) { - if (count > size()) { - if (count > capacity()) reserve(count * 2); - for (size_t i = size(); i != count; ++i) - alloc.construct(first_free++, s); - } - else if (count < size()) { - while (first_free != elements + count) - alloc.destroy(--first_free); - } + if (count > size()) { + if (count > capacity()) reserve(count * 2); + for (size_t i = size(); i != count; ++i) + alloc.construct(first_free++, s); + } + else if (count < size()) { + while (first_free != elements + count) alloc.destroy(--first_free); + } } -StrVec::StrVec(StrVec &&s) NOEXCEPT : elements(s.elements), first_free(s.first_free), cap(s.cap) +StrVec::StrVec(StrVec&& s) NOEXCEPT : elements(s.elements), + first_free(s.first_free), + cap(s.cap) { - // leave s in a state in which it is safe to run the destructor. - s.elements = s.first_free = s.cap = nullptr; + // leave s in a state in which it is safe to run the destructor. + s.elements = s.first_free = s.cap = nullptr; } -StrVec& StrVec::operator = (StrVec &&rhs) NOEXCEPT +StrVec& StrVec::operator=(StrVec&& rhs) NOEXCEPT { - if (this != &rhs) { - free(); - elements = rhs.elements; - first_free = rhs.first_free; - cap = rhs.cap; - rhs.elements = rhs.first_free = rhs.cap = nullptr; - } - return *this; + if (this != &rhs) { + free(); + elements = rhs.elements; + first_free = rhs.first_free; + cap = rhs.cap; + rhs.elements = rhs.first_free = rhs.cap = nullptr; + } + return *this; } -bool operator==(const StrVec &lhs, const StrVec &rhs) +bool operator==(const StrVec& lhs, const StrVec& rhs) { - return (lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin())); + return (lhs.size() == rhs.size() && + std::equal(lhs.begin(), lhs.end(), rhs.begin())); } -bool operator!=(const StrVec &lhs, const StrVec &rhs) +bool operator!=(const StrVec& lhs, const StrVec& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator<(const StrVec &lhs, const StrVec &rhs) +bool operator<(const StrVec& lhs, const StrVec& rhs) { - return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); + return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), + rhs.end()); } -bool operator>(const StrVec &lhs, const StrVec &rhs) +bool operator>(const StrVec& lhs, const StrVec& rhs) { - return rhs < lhs; + return rhs < lhs; } -bool operator<=(const StrVec &lhs, const StrVec &rhs) +bool operator<=(const StrVec& lhs, const StrVec& rhs) { - return !(rhs < lhs); + return !(rhs < lhs); } -bool operator>=(const StrVec &lhs, const StrVec &rhs) +bool operator>=(const StrVec& lhs, const StrVec& rhs) { - return !(lhs < rhs); + return !(lhs < rhs); } diff --git a/ch14/ex14_18_StrVec.h b/ch14/ex14_18_StrVec.h index 19036b9d..1c7cc899 100644 --- a/ch14/ex14_18_StrVec.h +++ b/ch14/ex14_18_StrVec.h @@ -11,56 +11,59 @@ #define NOEXCEPT #endif -class StrVec -{ - friend bool operator==(const StrVec&, const StrVec&); - friend bool operator!=(const StrVec&, const StrVec&); - friend bool operator< (const StrVec&, const StrVec&); - friend bool operator> (const StrVec&, const StrVec&); - friend bool operator<=(const StrVec&, const StrVec&); - friend bool operator>=(const StrVec&, const StrVec&); +class StrVec { + friend bool operator==(const StrVec&, const StrVec&); + friend bool operator!=(const StrVec&, const StrVec&); + friend bool operator<(const StrVec&, const StrVec&); + friend bool operator>(const StrVec&, const StrVec&); + friend bool operator<=(const StrVec&, const StrVec&); + friend bool operator>=(const StrVec&, const StrVec&); public: - StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} - StrVec(std::initializer_list); - StrVec(const StrVec&); - StrVec& operator=(const StrVec&); - StrVec(StrVec&&) NOEXCEPT; - StrVec& operator=(StrVec&&) NOEXCEPT; - ~StrVec(); + StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} + StrVec(std::initializer_list); + StrVec(const StrVec&); + StrVec& operator=(const StrVec&); + StrVec(StrVec&&) NOEXCEPT; + StrVec& operator=(StrVec&&) NOEXCEPT; + ~StrVec(); - void push_back(const std::string&); - size_t size() const { return first_free - elements; } - size_t capacity() const { return cap - elements; } - std::string *begin() const { return elements; } - std::string *end() const { return first_free; } + void push_back(const std::string&); + size_t size() const { return first_free - elements; } + size_t capacity() const { return cap - elements; } + std::string* begin() const { return elements; } + std::string* end() const { return first_free; } - std::string& at(size_t pos) { return *(elements + pos); } - const std::string& at(size_t pos) const { return *(elements + pos); } + std::string& at(size_t pos) { return *(elements + pos); } + const std::string& at(size_t pos) const { return *(elements + pos); } - void reserve(size_t new_cap); - void resize(size_t count); - void resize(size_t count, const std::string&); + void reserve(size_t new_cap); + void resize(size_t count); + void resize(size_t count, const std::string&); private: - std::pair alloc_n_copy(const std::string*, const std::string*); - void free(); - void chk_n_alloc() { if (size() == capacity()) reallocate(); } - void reallocate(); - void alloc_n_move(size_t new_cap); - void range_initialize(const std::string*, const std::string*); + std::pair alloc_n_copy(const std::string*, + const std::string*); + void free(); + void chk_n_alloc() + { + if (size() == capacity()) reallocate(); + } + void reallocate(); + void alloc_n_move(size_t new_cap); + void range_initialize(const std::string*, const std::string*); private: - std::string *elements; - std::string *first_free; - std::string *cap; - std::allocator alloc; + std::string* elements; + std::string* first_free; + std::string* cap; + std::allocator alloc; }; bool operator==(const StrVec&, const StrVec&); bool operator!=(const StrVec&, const StrVec&); -bool operator< (const StrVec&, const StrVec&); -bool operator> (const StrVec&, const StrVec&); +bool operator<(const StrVec&, const StrVec&); +bool operator>(const StrVec&, const StrVec&); bool operator<=(const StrVec&, const StrVec&); bool operator>=(const StrVec&, const StrVec&); diff --git a/ch14/ex14_18_StrVecMain.cpp b/ch14/ex14_18_StrVecMain.cpp index 8b3214a3..c8b16d77 100644 --- a/ch14/ex14_18_StrVecMain.cpp +++ b/ch14/ex14_18_StrVecMain.cpp @@ -4,43 +4,42 @@ int main() { - StrVec vec; - vec.reserve(6); - std::cout << "capacity(reserve to 6): " << vec.capacity() << std::endl; + StrVec vec; + vec.reserve(6); + std::cout << "capacity(reserve to 6): " << vec.capacity() << std::endl; - vec.reserve(4); - std::cout << "capacity(reserve to 4): " << vec.capacity() << std::endl; + vec.reserve(4); + std::cout << "capacity(reserve to 4): " << vec.capacity() << std::endl; - vec.push_back("hello"); - vec.push_back("world"); + vec.push_back("hello"); + vec.push_back("world"); - vec.resize(4); + vec.resize(4); - for (auto i = vec.begin(); i != vec.end(); ++i) - std::cout << *i << std::endl; - std::cout << "-EOF-" << std::endl; + for (auto i = vec.begin(); i != vec.end(); ++i) + std::cout << *i << std::endl; + std::cout << "-EOF-" << std::endl; - vec.resize(1); + vec.resize(1); - for (auto i = vec.begin(); i != vec.end(); ++i) - std::cout << *i << std::endl; - std::cout << "-EOF-" << std::endl; + for (auto i = vec.begin(); i != vec.end(); ++i) + std::cout << *i << std::endl; + std::cout << "-EOF-" << std::endl; - StrVec vec_list{"hello", "world", "pezy"}; + StrVec vec_list{"hello", "world", "pezy"}; - for (auto i = vec_list.begin(); i != vec_list.end(); ++i) - std::cout << *i << " "; - std::cout << std::endl; + for (auto i = vec_list.begin(); i != vec_list.end(); ++i) + std::cout << *i << " "; + std::cout << std::endl; - // Test operator== + // Test operator== - const StrVec const_vec_list{ "hello", "world", "pezy" }; - if (vec_list == const_vec_list) - for (const auto &str : const_vec_list) - std::cout << str << " "; - std::cout << std::endl; + const StrVec const_vec_list{"hello", "world", "pezy"}; + if (vec_list == const_vec_list) + for (const auto& str : const_vec_list) std::cout << str << " "; + std::cout << std::endl; - // Test operator< - const StrVec const_vec_list_small{"hello", "pezy", "ok"}; - std::cout << (const_vec_list_small < const_vec_list) << std::endl; + // Test operator< + const StrVec const_vec_list_small{"hello", "pezy", "ok"}; + std::cout << (const_vec_list_small < const_vec_list) << std::endl; } diff --git a/ch14/ex14_18_String.cpp b/ch14/ex14_18_String.cpp index de23e0b8..4bc8a90e 100644 --- a/ch14/ex14_18_String.cpp +++ b/ch14/ex14_18_String.cpp @@ -7,48 +7,50 @@ // //=========================================================================== -std::ostream& operator<<(std::ostream &os, const String &lhs) +std::ostream& operator<<(std::ostream& os, const String& lhs) { - os << lhs.c_str(); - return os; + os << lhs.c_str(); + return os; } -std::istream& operator>>(std::istream &is, String &rhs) +std::istream& operator>>(std::istream& is, String& rhs) { - for (char c; (c = is.get()) != '\n'; ) { - rhs.push_back(c); - } - return is; + for (char c; (c = is.get()) != '\n';) { + rhs.push_back(c); + } + return is; } -bool operator==(const String &lhs, const String &rhs) +bool operator==(const String& lhs, const String& rhs) { - return (lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin())); + return (lhs.size() == rhs.size() && + std::equal(lhs.begin(), lhs.end(), rhs.begin())); } -bool operator!=(const String &lhs, const String &rhs) +bool operator!=(const String& lhs, const String& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator<(const String &lhs, const String &rhs) +bool operator<(const String& lhs, const String& rhs) { - return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); + return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), + rhs.end()); } -bool operator>(const String &lhs, const String &rhs) +bool operator>(const String& lhs, const String& rhs) { - return rhs < lhs; + return rhs < lhs; } -bool operator<=(const String &lhs, const String &rhs) +bool operator<=(const String& lhs, const String& rhs) { - return !(rhs < lhs); + return !(rhs < lhs); } -bool operator>=(const String &lhs, const String &rhs) +bool operator>=(const String& lhs, const String& rhs) { - return !(lhs < rhs); + return !(lhs < rhs); } //=========================================================================== @@ -57,12 +59,11 @@ bool operator>=(const String &lhs, const String &rhs) // //=========================================================================== -String::String(const char *s) +String::String(const char* s) { - char *sl = const_cast(s); - while (*sl) - ++sl; - range_initializer(s, ++sl); + char* sl = const_cast(s); + while (*sl) ++sl; + range_initializer(s, ++sl); } //=========================================================================== @@ -73,40 +74,43 @@ String::String(const char *s) String::String(const String& rhs) { - range_initializer(rhs.elements, rhs.first_free); + range_initializer(rhs.elements, rhs.first_free); } -String& String::operator = (const String &rhs) +String& String::operator=(const String& rhs) { - auto newstr = alloc_n_copy(rhs.elements, rhs.first_free); - free(); - elements = newstr.first; - first_free = cap = newstr.second; - last_elem = first_free - 1; - return *this; + auto newstr = alloc_n_copy(rhs.elements, rhs.first_free); + free(); + elements = newstr.first; + first_free = cap = newstr.second; + last_elem = first_free - 1; + return *this; } -String::String(String &&s) NOEXCEPT : elements(s.elements), last_elem(s.last_elem), first_free(s.first_free), cap(s.cap) +String::String(String&& s) NOEXCEPT : elements(s.elements), + last_elem(s.last_elem), + first_free(s.first_free), + cap(s.cap) { - s.elements = s.last_elem = s.first_free = s.cap = nullptr; + s.elements = s.last_elem = s.first_free = s.cap = nullptr; } -String& String::operator = (String &&rhs) NOEXCEPT +String& String::operator=(String&& rhs) NOEXCEPT { - if (this != &rhs) { - free(); - elements = rhs.elements; - last_elem = rhs.last_elem; - first_free = rhs.first_free; - cap = rhs.cap; - rhs.elements = rhs.last_elem = rhs.first_free = rhs.cap = nullptr; - } - return *this; + if (this != &rhs) { + free(); + elements = rhs.elements; + last_elem = rhs.last_elem; + first_free = rhs.first_free; + cap = rhs.cap; + rhs.elements = rhs.last_elem = rhs.first_free = rhs.cap = nullptr; + } + return *this; } String::~String() { - free(); + free(); } //=========================================================================== @@ -117,86 +121,85 @@ String::~String() void String::push_back(const char c) { - chk_n_alloc(); - *last_elem = c; - last_elem = first_free; - alloc.construct(first_free++, '\0'); + chk_n_alloc(); + *last_elem = c; + last_elem = first_free; + alloc.construct(first_free++, '\0'); } void String::reallocate() { - // \0 | - - // ^ ^ - // elements first_free - // last_elem cap + // \0 | - + // ^ ^ + // elements first_free + // last_elem cap - auto newcapacity = size() ? 2 * (size() + 1) : 2; - alloc_n_move(newcapacity); + auto newcapacity = size() ? 2 * (size() + 1) : 2; + alloc_n_move(newcapacity); } void String::alloc_n_move(size_t new_cap) { - auto newdata = alloc.allocate(new_cap); - auto dest = newdata; - auto elem = elements; - for (size_t i = 0; i != size() + 1; ++i) - alloc.construct(dest++, std::move(*elem++)); - free(); - elements = newdata; - last_elem = dest - 1; - first_free = dest; - cap = elements + new_cap; + auto newdata = alloc.allocate(new_cap); + auto dest = newdata; + auto elem = elements; + for (size_t i = 0; i != size() + 1; ++i) + alloc.construct(dest++, std::move(*elem++)); + free(); + elements = newdata; + last_elem = dest - 1; + first_free = dest; + cap = elements + new_cap; } void String::free() { - if (elements) { - std::for_each(elements, first_free, [this](char &c){ alloc.destroy(&c); }); - alloc.deallocate(elements, cap - elements); - } + if (elements) { + std::for_each(elements, first_free, + [this](char& c) { alloc.destroy(&c); }); + alloc.deallocate(elements, cap - elements); + } } -std::pair -String::alloc_n_copy(const char *b, const char *e) +std::pair String::alloc_n_copy(const char* b, const char* e) { - auto str = alloc.allocate(e-b); - return{ str, std::uninitialized_copy(b, e, str)}; + auto str = alloc.allocate(e - b); + return {str, std::uninitialized_copy(b, e, str)}; } -void String::range_initializer(const char *first, const char *last) +void String::range_initializer(const char* first, const char* last) { - auto newstr = alloc_n_copy(first, last); - elements = newstr.first; - first_free = cap = newstr.second; - last_elem = first_free - 1; + auto newstr = alloc_n_copy(first, last); + elements = newstr.first; + first_free = cap = newstr.second; + last_elem = first_free - 1; } void String::reserve(size_t new_cap) { - if (new_cap <= capacity()) return; - alloc_n_move(new_cap); + if (new_cap <= capacity()) return; + alloc_n_move(new_cap); } void String::resize(size_t count, char c) { - if (count > size()) { - if (count > capacity()) reserve(count * 2); - for (size_t i = size(); i != count; ++i) { - *last_elem++ = c; - alloc.construct(first_free++, '\0'); - } - - } - else if (count < size()) { - while (last_elem != elements + count) { - --last_elem; - alloc.destroy(--first_free); - } - *last_elem = '\0'; - } + if (count > size()) { + if (count > capacity()) reserve(count * 2); + for (size_t i = size(); i != count; ++i) { + *last_elem++ = c; + alloc.construct(first_free++, '\0'); + } + } + else if (count < size()) { + while (last_elem != elements + count) { + --last_elem; + alloc.destroy(--first_free); + } + *last_elem = '\0'; + } } void String::resize(size_t count) { - resize(count, ' '); + resize(count, ' '); } diff --git a/ch14/ex14_18_String.h b/ch14/ex14_18_String.h index 1727f20a..6ba68531 100644 --- a/ch14/ex14_18_String.h +++ b/ch14/ex14_18_String.h @@ -18,62 +18,64 @@ // //=================================================================================== -class String -{ - friend std::ostream& operator<<(std::ostream&, const String&); - friend std::istream& operator>>(std::istream&, String&); - friend bool operator==(const String&, const String&); - friend bool operator!=(const String&, const String&); - friend bool operator< (const String&, const String&); - friend bool operator> (const String&, const String&); - friend bool operator<=(const String&, const String&); - friend bool operator>=(const String&, const String&); +class String { + friend std::ostream& operator<<(std::ostream&, const String&); + friend std::istream& operator>>(std::istream&, String&); + friend bool operator==(const String&, const String&); + friend bool operator!=(const String&, const String&); + friend bool operator<(const String&, const String&); + friend bool operator>(const String&, const String&); + friend bool operator<=(const String&, const String&); + friend bool operator>=(const String&, const String&); public: - String() : String("") {} - String(const char *); - String(const String&); - String& operator=(const String&); - String(String &&) NOEXCEPT; - String& operator=(String&&) NOEXCEPT; - ~String(); + String() : String("") {} + String(const char*); + String(const String&); + String& operator=(const String&); + String(String&&) NOEXCEPT; + String& operator=(String&&) NOEXCEPT; + ~String(); - void push_back(const char); + void push_back(const char); - char* begin() const { return elements; } - char* end() const { return last_elem; } + char* begin() const { return elements; } + char* end() const { return last_elem; } - const char *c_str() const { return elements; } - size_t size() const { return last_elem - elements; } - size_t length() const { return size(); } - size_t capacity() const { return cap - elements; } + const char* c_str() const { return elements; } + size_t size() const { return last_elem - elements; } + size_t length() const { return size(); } + size_t capacity() const { return cap - elements; } - void reserve(size_t); - void resize(size_t); - void resize(size_t, char); + void reserve(size_t); + void resize(size_t); + void resize(size_t, char); private: - std::pair alloc_n_copy(const char*, const char*); - void range_initializer(const char*, const char*); - void free(); - void reallocate(); - void alloc_n_move(size_t new_cap); - void chk_n_alloc() { if (first_free == cap) reallocate(); } + std::pair alloc_n_copy(const char*, const char*); + void range_initializer(const char*, const char*); + void free(); + void reallocate(); + void alloc_n_move(size_t new_cap); + void chk_n_alloc() + { + if (first_free == cap) reallocate(); + } private: - char *elements; - char *last_elem; - char *first_free; - char *cap; - std::allocator alloc; + char* elements; + char* last_elem; + char* first_free; + char* cap; + std::allocator alloc; }; std::ostream& operator<<(std::ostream&, const String&); std::istream& operator>>(std::istream&, String&); bool operator==(const String&, const String&); bool operator!=(const String&, const String&); -bool operator< (const String&, const String&); -bool operator> (const String&, const String&); +bool operator<(const String&, const String&); +bool operator>(const String&, const String&); bool operator<=(const String&, const String&); bool operator>=(const String&, const String&); diff --git a/ch14/ex14_18_StringMain.cpp b/ch14/ex14_18_StringMain.cpp index 60792efd..a84826e4 100644 --- a/ch14/ex14_18_StringMain.cpp +++ b/ch14/ex14_18_StringMain.cpp @@ -7,58 +7,56 @@ void foo(String x) { - std::cout << x << std::endl; + std::cout << x << std::endl; } void bar(const String& x) { - std::cout << x.c_str() << std::endl; + std::cout << x.c_str() << std::endl; } String baz() { - String ret("world"); - return ret; + String ret("world"); + return ret; } int main() { - char text[] = "world"; - - String s0; - String s1("hello"); - String s2(std::move(s0)); - String s3 = s1; - String s4(text); - s2 = s1; - - if (s2 == s1) - std::cout << "s2 == s1" << std::endl; - - foo(s1); - bar(s1); - foo("temporary"); - bar("temporary"); - String s5 = baz(); - - std::vector svec; - //svec.push_back(s0); - svec.push_back(s1); - svec.push_back(s2); - svec.push_back(s3); - svec.push_back(s4); - svec.push_back(baz()); - svec.push_back("good job"); - - for (const auto &s : svec) { - std::cout << s << std::endl; - } - - std::cout << "Input a string: "; - String s6; - std::cin >> s6; - std::cout << s6 << std::endl; - - if (s6 > s1) - std::cout << "s6 > s1" << std::endl; + char text[] = "world"; + + String s0; + String s1("hello"); + String s2(std::move(s0)); + String s3 = s1; + String s4(text); + s2 = s1; + + if (s2 == s1) std::cout << "s2 == s1" << std::endl; + + foo(s1); + bar(s1); + foo("temporary"); + bar("temporary"); + String s5 = baz(); + + std::vector svec; + // svec.push_back(s0); + svec.push_back(s1); + svec.push_back(s2); + svec.push_back(s3); + svec.push_back(s4); + svec.push_back(baz()); + svec.push_back("good job"); + + for (const auto& s : svec) { + std::cout << s << std::endl; + } + + std::cout << "Input a string: "; + String s6; + std::cin >> s6; + std::cout << s6 << std::endl; + + if (s6 > s1) std::cout << "s6 > s1" << std::endl; } diff --git a/ch14/ex14_22.cpp b/ch14/ex14_22.cpp index a7622258..dc5d3f75 100644 --- a/ch14/ex14_22.cpp +++ b/ch14/ex14_22.cpp @@ -1,18 +1,18 @@ #include "ex14_22.h" -Sales_data::Sales_data(std::istream &is) : Sales_data() +Sales_data::Sales_data(std::istream& is) : Sales_data() { is >> *this; } -Sales_data& Sales_data::operator+=(const Sales_data &rhs) +Sales_data& Sales_data::operator+=(const Sales_data& rhs) { units_sold += rhs.units_sold; revenue += rhs.revenue; return *this; } -std::istream& operator>>(std::istream &is, Sales_data &item) +std::istream& operator>>(std::istream& is, Sales_data& item) { double price = 0.0; is >> item.bookNo >> item.units_sold >> price; @@ -23,20 +23,21 @@ std::istream& operator>>(std::istream &is, Sales_data &item) return is; } -std::ostream& operator<<(std::ostream &os, const Sales_data &item) +std::ostream& operator<<(std::ostream& os, const Sales_data& item) { - os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " << item.avg_price(); + os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " + << item.avg_price(); return os; } -Sales_data operator+(const Sales_data &lhs, const Sales_data &rhs) +Sales_data operator+(const Sales_data& lhs, const Sales_data& rhs) { Sales_data sum = lhs; sum += rhs; return sum; } -Sales_data& Sales_data::operator=(const std::string &isbn) +Sales_data& Sales_data::operator=(const std::string& isbn) { *this = Sales_data(isbn); return *this; diff --git a/ch14/ex14_22.h b/ch14/ex14_22.h index a25ee272..9b44f808 100644 --- a/ch14/ex14_22.h +++ b/ch14/ex14_22.h @@ -23,10 +23,13 @@ class Sales_data { friend Sales_data operator+(const Sales_data&, const Sales_data&); public: - Sales_data(const std::string &s, unsigned n, double p):bookNo(s),units_sold(n),revenue(n*p){} - Sales_data() : Sales_data("", 0, 0.0f){} - Sales_data(const std::string &s) : Sales_data(s, 0, 0.0f){} - Sales_data(std::istream &is); + Sales_data(const std::string& s, unsigned n, double p) + : bookNo(s), units_sold(n), revenue(n * p) + { + } + Sales_data() : Sales_data("", 0, 0.0f) {} + Sales_data(const std::string& s) : Sales_data(s, 0, 0.0f) {} + Sales_data(std::istream& is); Sales_data& operator=(const std::string&); @@ -47,7 +50,7 @@ Sales_data operator+(const Sales_data&, const Sales_data&); inline double Sales_data::avg_price() const { - return units_sold ? revenue/units_sold : 0; + return units_sold ? revenue / units_sold : 0; } #endif diff --git a/ch14/ex14_23.cpp b/ch14/ex14_23.cpp index 4fd5a375..0eff57f0 100644 --- a/ch14/ex14_23.cpp +++ b/ch14/ex14_23.cpp @@ -1,151 +1,155 @@ #include "ex14_23.h" #include // for_each, equal -void StrVec::push_back(const std::string &s) +void StrVec::push_back(const std::string& s) { - chk_n_alloc(); - alloc.construct(first_free++, s); + chk_n_alloc(); + alloc.construct(first_free++, s); } -std::pair -StrVec::alloc_n_copy(const std::string *b, const std::string *e) +std::pair StrVec::alloc_n_copy(const std::string* b, + const std::string* e) { - auto data = alloc.allocate(e-b); - return { data, std::uninitialized_copy(b, e, data) }; + auto data = alloc.allocate(e - b); + return {data, std::uninitialized_copy(b, e, data)}; } void StrVec::free() { - if (elements) { - for_each(elements, first_free, [this](std::string &rhs){ alloc.destroy(&rhs); }); - alloc.deallocate(elements, cap - elements); - } + if (elements) { + for_each(elements, first_free, + [this](std::string& rhs) { alloc.destroy(&rhs); }); + alloc.deallocate(elements, cap - elements); + } } -void StrVec::range_initialize(const std::string *first, const std::string *last) +void StrVec::range_initialize(const std::string* first, const std::string* last) { - auto newdata = alloc_n_copy(first, last); - elements = newdata.first; - first_free = cap = newdata.second; + auto newdata = alloc_n_copy(first, last); + elements = newdata.first; + first_free = cap = newdata.second; } -StrVec::StrVec(const StrVec &rhs) +StrVec::StrVec(const StrVec& rhs) { - range_initialize(rhs.begin(), rhs.end()); + range_initialize(rhs.begin(), rhs.end()); } StrVec::StrVec(std::initializer_list il) { - range_initialize(il.begin(), il.end()); + range_initialize(il.begin(), il.end()); } StrVec::~StrVec() { - free(); + free(); } -StrVec& StrVec::operator = (const StrVec &rhs) +StrVec& StrVec::operator=(const StrVec& rhs) { - auto data = alloc_n_copy(rhs.begin(), rhs.end()); - free(); - elements = data.first; - first_free = cap = data.second; - return *this; + auto data = alloc_n_copy(rhs.begin(), rhs.end()); + free(); + elements = data.first; + first_free = cap = data.second; + return *this; } void StrVec::alloc_n_move(size_t new_cap) { - auto newdata = alloc.allocate(new_cap); - auto dest = newdata; - auto elem = elements; - for (size_t i = 0; i != size(); ++i) - alloc.construct(dest++, std::move(*elem++)); - free(); - elements = newdata; - first_free = dest; - cap = elements + new_cap; + auto newdata = alloc.allocate(new_cap); + auto dest = newdata; + auto elem = elements; + for (size_t i = 0; i != size(); ++i) + alloc.construct(dest++, std::move(*elem++)); + free(); + elements = newdata; + first_free = dest; + cap = elements + new_cap; } void StrVec::reallocate() { - auto newcapacity = size() ? 2 * size() : 1; - alloc_n_move(newcapacity); + auto newcapacity = size() ? 2 * size() : 1; + alloc_n_move(newcapacity); } void StrVec::reserve(size_t new_cap) { - if (new_cap <= capacity()) return; - alloc_n_move(new_cap); + if (new_cap <= capacity()) return; + alloc_n_move(new_cap); } void StrVec::resize(size_t count) { - resize(count, std::string()); + resize(count, std::string()); } -void StrVec::resize(size_t count, const std::string &s) +void StrVec::resize(size_t count, const std::string& s) { - if (count > size()) { - if (count > capacity()) reserve(count * 2); - for (size_t i = size(); i != count; ++i) - alloc.construct(first_free++, s); - } - else if (count < size()) { - while (first_free != elements + count) - alloc.destroy(--first_free); - } + if (count > size()) { + if (count > capacity()) reserve(count * 2); + for (size_t i = size(); i != count; ++i) + alloc.construct(first_free++, s); + } + else if (count < size()) { + while (first_free != elements + count) alloc.destroy(--first_free); + } } -StrVec::StrVec(StrVec &&s) NOEXCEPT : elements(s.elements), first_free(s.first_free), cap(s.cap) +StrVec::StrVec(StrVec&& s) NOEXCEPT : elements(s.elements), + first_free(s.first_free), + cap(s.cap) { - // leave s in a state in which it is safe to run the destructor. - s.elements = s.first_free = s.cap = nullptr; + // leave s in a state in which it is safe to run the destructor. + s.elements = s.first_free = s.cap = nullptr; } -StrVec& StrVec::operator = (StrVec &&rhs) NOEXCEPT +StrVec& StrVec::operator=(StrVec&& rhs) NOEXCEPT { - if (this != &rhs) { - free(); - elements = rhs.elements; - first_free = rhs.first_free; - cap = rhs.cap; - rhs.elements = rhs.first_free = rhs.cap = nullptr; - } - return *this; + if (this != &rhs) { + free(); + elements = rhs.elements; + first_free = rhs.first_free; + cap = rhs.cap; + rhs.elements = rhs.first_free = rhs.cap = nullptr; + } + return *this; } -bool operator==(const StrVec &lhs, const StrVec &rhs) +bool operator==(const StrVec& lhs, const StrVec& rhs) { - return (lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin())); + return (lhs.size() == rhs.size() && + std::equal(lhs.begin(), lhs.end(), rhs.begin())); } -bool operator!=(const StrVec &lhs, const StrVec &rhs) +bool operator!=(const StrVec& lhs, const StrVec& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator<(const StrVec &lhs, const StrVec &rhs) +bool operator<(const StrVec& lhs, const StrVec& rhs) { - return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); + return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), + rhs.end()); } -bool operator>(const StrVec &lhs, const StrVec &rhs) +bool operator>(const StrVec& lhs, const StrVec& rhs) { - return rhs < lhs; + return rhs < lhs; } -bool operator<=(const StrVec &lhs, const StrVec &rhs) +bool operator<=(const StrVec& lhs, const StrVec& rhs) { - return !(rhs < lhs); + return !(rhs < lhs); } -bool operator>=(const StrVec &lhs, const StrVec &rhs) +bool operator>=(const StrVec& lhs, const StrVec& rhs) { - return !(lhs < rhs); + return !(lhs < rhs); } StrVec& StrVec::operator=(std::initializer_list il) { - *this = StrVec(il); - return *this; + *this = StrVec(il); + return *this; } diff --git a/ch14/ex14_23.h b/ch14/ex14_23.h index 31fb8eb4..a36fc98f 100644 --- a/ch14/ex14_23.h +++ b/ch14/ex14_23.h @@ -11,58 +11,61 @@ #define NOEXCEPT #endif -class StrVec -{ - friend bool operator==(const StrVec&, const StrVec&); - friend bool operator!=(const StrVec&, const StrVec&); - friend bool operator< (const StrVec&, const StrVec&); - friend bool operator> (const StrVec&, const StrVec&); - friend bool operator<=(const StrVec&, const StrVec&); - friend bool operator>=(const StrVec&, const StrVec&); +class StrVec { + friend bool operator==(const StrVec&, const StrVec&); + friend bool operator!=(const StrVec&, const StrVec&); + friend bool operator<(const StrVec&, const StrVec&); + friend bool operator>(const StrVec&, const StrVec&); + friend bool operator<=(const StrVec&, const StrVec&); + friend bool operator>=(const StrVec&, const StrVec&); public: - StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} - StrVec(std::initializer_list); - StrVec(const StrVec&); - StrVec& operator=(const StrVec&); - StrVec(StrVec&&) NOEXCEPT; - StrVec& operator=(StrVec&&) NOEXCEPT; - ~StrVec(); + StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} + StrVec(std::initializer_list); + StrVec(const StrVec&); + StrVec& operator=(const StrVec&); + StrVec(StrVec&&) NOEXCEPT; + StrVec& operator=(StrVec&&) NOEXCEPT; + ~StrVec(); - StrVec& operator=(std::initializer_list); + StrVec& operator=(std::initializer_list); - void push_back(const std::string&); - size_t size() const { return first_free - elements; } - size_t capacity() const { return cap - elements; } - std::string *begin() const { return elements; } - std::string *end() const { return first_free; } + void push_back(const std::string&); + size_t size() const { return first_free - elements; } + size_t capacity() const { return cap - elements; } + std::string* begin() const { return elements; } + std::string* end() const { return first_free; } - std::string& at(size_t pos) { return *(elements + pos); } - const std::string& at(size_t pos) const { return *(elements + pos); } + std::string& at(size_t pos) { return *(elements + pos); } + const std::string& at(size_t pos) const { return *(elements + pos); } - void reserve(size_t new_cap); - void resize(size_t count); - void resize(size_t count, const std::string&); + void reserve(size_t new_cap); + void resize(size_t count); + void resize(size_t count, const std::string&); private: - std::pair alloc_n_copy(const std::string*, const std::string*); - void free(); - void chk_n_alloc() { if (size() == capacity()) reallocate(); } - void reallocate(); - void alloc_n_move(size_t new_cap); - void range_initialize(const std::string*, const std::string*); + std::pair alloc_n_copy(const std::string*, + const std::string*); + void free(); + void chk_n_alloc() + { + if (size() == capacity()) reallocate(); + } + void reallocate(); + void alloc_n_move(size_t new_cap); + void range_initialize(const std::string*, const std::string*); private: - std::string *elements; - std::string *first_free; - std::string *cap; - std::allocator alloc; + std::string* elements; + std::string* first_free; + std::string* cap; + std::allocator alloc; }; bool operator==(const StrVec&, const StrVec&); bool operator!=(const StrVec&, const StrVec&); -bool operator< (const StrVec&, const StrVec&); -bool operator> (const StrVec&, const StrVec&); +bool operator<(const StrVec&, const StrVec&); +bool operator>(const StrVec&, const StrVec&); bool operator<=(const StrVec&, const StrVec&); bool operator>=(const StrVec&, const StrVec&); diff --git a/ch14/ex14_23_TEST.cpp b/ch14/ex14_23_TEST.cpp index 3bff1a8e..e13782ee 100644 --- a/ch14/ex14_23_TEST.cpp +++ b/ch14/ex14_23_TEST.cpp @@ -4,43 +4,42 @@ int main() { - StrVec vec; - vec.reserve(6); - std::cout << "capacity(reserve to 6): " << vec.capacity() << std::endl; + StrVec vec; + vec.reserve(6); + std::cout << "capacity(reserve to 6): " << vec.capacity() << std::endl; - vec.reserve(4); - std::cout << "capacity(reserve to 4): " << vec.capacity() << std::endl; + vec.reserve(4); + std::cout << "capacity(reserve to 4): " << vec.capacity() << std::endl; - vec.push_back("hello"); - vec.push_back("world"); + vec.push_back("hello"); + vec.push_back("world"); - vec.resize(4); + vec.resize(4); - for (auto i = vec.begin(); i != vec.end(); ++i) - std::cout << *i << std::endl; - std::cout << "-EOF-" << std::endl; + for (auto i = vec.begin(); i != vec.end(); ++i) + std::cout << *i << std::endl; + std::cout << "-EOF-" << std::endl; - vec.resize(1); + vec.resize(1); - for (auto i = vec.begin(); i != vec.end(); ++i) - std::cout << *i << std::endl; - std::cout << "-EOF-" << std::endl; + for (auto i = vec.begin(); i != vec.end(); ++i) + std::cout << *i << std::endl; + std::cout << "-EOF-" << std::endl; - StrVec vec_list{"hello", "world", "pezy"}; + StrVec vec_list{"hello", "world", "pezy"}; - for (auto i = vec_list.begin(); i != vec_list.end(); ++i) - std::cout << *i << " "; - std::cout << std::endl; + for (auto i = vec_list.begin(); i != vec_list.end(); ++i) + std::cout << *i << " "; + std::cout << std::endl; - // Test operator== + // Test operator== - const StrVec const_vec_list = { "hello", "world", "pezy" }; - if (vec_list == const_vec_list) - for (const auto &str : const_vec_list) - std::cout << str << " "; - std::cout << std::endl; + const StrVec const_vec_list = {"hello", "world", "pezy"}; + if (vec_list == const_vec_list) + for (const auto& str : const_vec_list) std::cout << str << " "; + std::cout << std::endl; - // Test operator< - const StrVec const_vec_list_small = {"hello", "pezy", "ok"}; - std::cout << (const_vec_list_small < const_vec_list) << std::endl; + // Test operator< + const StrVec const_vec_list_small = {"hello", "pezy", "ok"}; + std::cout << (const_vec_list_small < const_vec_list) << std::endl; } diff --git a/ch14/ex14_24.cpp b/ch14/ex14_24.cpp index 8dd46961..58ecdc2d 100644 --- a/ch14/ex14_24.cpp +++ b/ch14/ex14_24.cpp @@ -6,31 +6,32 @@ Date::Date(Size days) { //! calculate the year - Size y400 = days/YtoD_400; - Size y100 = (days - y400*YtoD_400)/YtoD_100; - Size y4 = (days - y400*YtoD_400 - y100*YtoD_100)/YtoD_4; - Size y = (days - y400*YtoD_400 - y100*YtoD_100 - y4*YtoD_4)/365; - Size d = days - y400*YtoD_400 - y100*YtoD_100 - y4*YtoD_4 - y*365; - this->year = y400*400 + y100*100 + y4*4 + y; + Size y400 = days / YtoD_400; + Size y100 = (days - y400 * YtoD_400) / YtoD_100; + Size y4 = (days - y400 * YtoD_400 - y100 * YtoD_100) / YtoD_4; + Size y = (days - y400 * YtoD_400 - y100 * YtoD_100 - y4 * YtoD_4) / 365; + Size d = days - y400 * YtoD_400 - y100 * YtoD_100 - y4 * YtoD_4 - y * 365; + this->year = y400 * 400 + y100 * 100 + y4 * 4 + y; //! check if leap and choose the months vector accordingly - std::vectorcurrYear - = isLeapYear(this->year) ? monthsVec_l : monthsVec_n; + std::vector currYear = + isLeapYear(this->year) ? monthsVec_l : monthsVec_n; //! calculate day and month using find_if + lambda Size D_accumu = 0, M_accumu = 0; - //! @bug fixed: the variabbles above hade been declared inside the find_if as static - //! which caused the bug. It works fine now after being move outside. + //! @bug fixed: the variabbles above hade been declared inside the + //! find_if as static + //! which caused the bug. It works fine now after being move + //! outside. - std::find_if(currYear.cbegin(), currYear.cend(), [&](Size m){ + std::find_if(currYear.cbegin(), currYear.cend(), [&](Size m) { D_accumu += m; - M_accumu ++; + M_accumu++; - if(d < D_accumu) - { - this->month = M_accumu; - this->day = d + m - D_accumu ; + if (d < D_accumu) { + this->month = M_accumu; + this->day = d + m - D_accumu; return true; } @@ -40,55 +41,52 @@ Date::Date(Size days) } //! construcotr taking iostream -Date::Date(std::istream &is, std::ostream &os) +Date::Date(std::istream& is, std::ostream& os) { is >> day >> month >> year; - if(is) - { - if(check(*this)) return; - else - { + if (is) { + if (check(*this)) + return; + else { os << "Invalid input! Object is default initialized."; *this = Date(); } } - else - { + else { os << "Invalid input! Object is default initialized."; *this = Date(); } - } //! copy constructor -Date::Date(const Date &d) : - day(d.day), month(d.month), year(d.year) -{} +Date::Date(const Date& d) : day(d.day), month(d.month), year(d.year) +{ +} //! move constructor -Date::Date(Date&& d) NOEXCEPT : - day(d.day), month(d.month), year(d.year) -{ std::cout << "copy moving";} +Date::Date(Date&& d) NOEXCEPT : day(d.day), month(d.month), year(d.year) +{ + std::cout << "copy moving"; +} //! copy operator= -Date &Date::operator= (const Date &d) +Date& Date::operator=(const Date& d) { - this->day = d.day; + this->day = d.day; this->month = d.month; - this->year = d.year; + this->year = d.year; return *this; } //! move operator= -Date &Date::operator =(Date&& rhs) NOEXCEPT +Date& Date::operator=(Date&& rhs) NOEXCEPT { - if(this != &rhs) - { - this->day = rhs.day; + if (this != &rhs) { + this->day = rhs.day; this->month = rhs.month; - this->year = rhs.year; + this->year = rhs.year; } std::cout << "moving ="; @@ -101,33 +99,34 @@ Date::Size Date::toDays() const Size result = this->day; //! check if leap and choose the months vector accordingly - std::vectorcurrYear - = isLeapYear(this->year) ? monthsVec_l : monthsVec_n; + std::vector currYear = + isLeapYear(this->year) ? monthsVec_l : monthsVec_n; //! calculate result + days by months - for(auto it = currYear.cbegin(); it != currYear.cbegin() + this->month -1; ++it) + for (auto it = currYear.cbegin(); it != currYear.cbegin() + this->month - 1; + ++it) result += *it; //! calculate result + days by years - result += (this->year/400) * YtoD_400; - result += (this->year%400/100) * YtoD_100; - result += (this->year%100/4) * YtoD_4; - result += (this->year%4) * YtoD_1; + result += (this->year / 400) * YtoD_400; + result += (this->year % 400 / 100) * YtoD_100; + result += (this->year % 100 / 4) * YtoD_4; + result += (this->year % 4) * YtoD_1; return result; } //! member operators: += -= -Date &Date::operator +=(Date::Size offset) +Date& Date::operator+=(Date::Size offset) { *this = Date(this->toDays() + offset); return *this; } -Date &Date::operator -=(Date::Size offset) +Date& Date::operator-=(Date::Size offset) { - if(this->toDays() > offset) + if (this->toDays() > offset) *this = Date(this->toDays() - offset); else *this = Date(); @@ -137,71 +136,59 @@ Date &Date::operator -=(Date::Size offset) //! non-member operators: << >> - == != < <= > >= -std::ostream& -operator <<(std::ostream& os, const Date& d) +std::ostream& operator<<(std::ostream& os, const Date& d) { os << d.day << " " << d.month << " " << d.year; return os; } -std::istream& -operator >>(std::istream& is, Date& d) +std::istream& operator>>(std::istream& is, Date& d) { - if(is) - { + if (is) { Date input = Date(is, std::cout); - if(check(input)) d = input; + if (check(input)) d = input; } return is; } - -int operator -(const Date &lhs, const Date &rhs) +int operator-(const Date& lhs, const Date& rhs) { return lhs.toDays() - rhs.toDays(); } - -bool operator ==(const Date &lhs, const Date &rhs) +bool operator==(const Date& lhs, const Date& rhs) { - return (lhs.day == rhs.day ) && - (lhs.month == rhs.month) && - (lhs.year == rhs.year ) ; + return (lhs.day == rhs.day) && (lhs.month == rhs.month) && + (lhs.year == rhs.year); } - -bool operator !=(const Date &lhs, const Date &rhs) +bool operator!=(const Date& lhs, const Date& rhs) { return !(lhs == rhs); } - -bool operator < (const Date &lhs, const Date &rhs) +bool operator<(const Date& lhs, const Date& rhs) { return lhs.toDays() < rhs.toDays(); } - -bool operator <=(const Date &lhs, const Date &rhs) +bool operator<=(const Date& lhs, const Date& rhs) { return (lhs < rhs) || (lhs == rhs); } - -bool operator >(const Date &lhs, const Date &rhs) +bool operator>(const Date& lhs, const Date& rhs) { return !(lhs <= rhs); } - -bool operator >=(const Date &lhs, const Date &rhs) +bool operator>=(const Date& lhs, const Date& rhs) { return !(lhs < rhs); } - -Date operator - (const Date &lhs, Date::Size rhs) -{ //! ^^^ rhs must not be larger than 2^32-1 +Date operator-(const Date& lhs, Date::Size rhs) +{ //! ^^^ rhs must not be larger than 2^32-1 //! copy lhs Date result(lhs); result -= rhs; @@ -209,9 +196,8 @@ Date operator - (const Date &lhs, Date::Size rhs) return result; } - -Date operator + (const Date &lhs, Date::Size rhs) -{ //! ^^^ rhs must not be larger than 2^32-1 +Date operator+(const Date& lhs, Date::Size rhs) +{ //! ^^^ rhs must not be larger than 2^32-1 //! copy lhs Date result(lhs); result += rhs; diff --git a/ch14/ex14_24.h b/ch14/ex14_24.h index c8443e3e..4562d473 100644 --- a/ch14/ex14_24.h +++ b/ch14/ex14_24.h @@ -6,8 +6,10 @@ ***************************************************************************/ //! //! Exercise 7.40: -//! Choose one of the following abstractions (or an abstraction of your own choosing). -//! Determine what data are needed in the class. Provide an appropriate set of constructors. +//! Choose one of the following abstractions (or an abstraction of your own +//! choosing). +//! Determine what data are needed in the class. Provide an appropriate set of +//! constructors. //! Explain your decisions. //! //! Exercise 14.5: @@ -58,12 +60,12 @@ #include #include -class Date -{ - friend bool operator ==(const Date& lhs, const Date& rhs); - friend bool operator < (const Date &lhs, const Date &rhs); - friend bool check(const Date &d); - friend std::ostream& operator <<(std::ostream& os, const Date& d); +class Date { + friend bool operator==(const Date& lhs, const Date& rhs); + friend bool operator<(const Date& lhs, const Date& rhs); + friend bool check(const Date& d); + friend std::ostream& operator<<(std::ostream& os, const Date& d); + public: typedef std::size_t Size; @@ -72,9 +74,9 @@ class Date //! constructor taking Size as days explicit Date(Size days); //! constructor taking three Size - Date(Size d, Size m, Size y) : day(d), month(m), year(y) { } + Date(Size d, Size m, Size y) : day(d), month(m), year(y) {} //! constructor taking iostream - Date(std::istream &is, std::ostream &os); + Date(std::istream& is, std::ostream& os); //! copy constructor Date(const Date& d); @@ -82,133 +84,107 @@ class Date Date(Date&& d) NOEXCEPT; //! copy operator= - Date& operator= (const Date& d); + Date& operator=(const Date& d); //! move operator= - Date& operator= (Date&& rhs) NOEXCEPT; + Date& operator=(Date&& rhs) NOEXCEPT; //! destructor -- in this case, user-defined destructor is not nessary. - ~Date(){ std::cout << "destroying\n"; } + ~Date() { std::cout << "destroying\n"; } //! members - Size toDays() const; //not implemented yet. - Date& operator +=(Size offset); - Date& operator -=(Size offset); - + Size toDays() const; // not implemented yet. + Date& operator+=(Size offset); + Date& operator-=(Size offset); private: - Size day = 1; - Size month = 1; - Size year = 0; + Size day = 1; + Size month = 1; + Size year = 0; }; -static const Date::Size YtoD_400 = 146097; //365*400 + 400/4 -3 == 146097 -static const Date::Size YtoD_100 = 36524; //365*100 + 100/4 -1 == 36524 -static const Date::Size YtoD_4 = 1461; //365*4 + 1 == 1461 -static const Date::Size YtoD_1 = 365; //365 +static const Date::Size YtoD_400 = 146097; // 365*400 + 400/4 -3 == 146097 +static const Date::Size YtoD_100 = 36524; // 365*100 + 100/4 -1 == 36524 +static const Date::Size YtoD_4 = 1461; // 365*4 + 1 == 1461 +static const Date::Size YtoD_1 = 365; // 365 //! normal year -static const std::vector monthsVec_n = -{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; +static const std::vector monthsVec_n = {31, 28, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31}; //! leap year -static const std::vector monthsVec_l = -{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; +static const std::vector monthsVec_l = {31, 29, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31}; //! non-member operators: << >> - == != < <= > >= //! -std::ostream& -operator <<(std::ostream& os, const Date& d); -std::istream& -operator >>(std::istream& is, Date& d); -int -operator - (const Date& lhs, const Date& rhs); -bool -operator ==(const Date& lhs, const Date& rhs); -bool -operator !=(const Date& lhs, const Date& rhs); -bool -operator < (const Date& lhs, const Date& rhs); -bool -operator <=(const Date& lhs, const Date& rhs); -bool -operator >(const Date& lhs, const Date& rhs); -bool -operator >=(const Date& lhs, const Date& rhs); -Date -operator - (const Date& lhs, Date::Size rhs); -Date -operator +(const Date& lhs, Date::Size rhs); - - +std::ostream& operator<<(std::ostream& os, const Date& d); +std::istream& operator>>(std::istream& is, Date& d); +int operator-(const Date& lhs, const Date& rhs); +bool operator==(const Date& lhs, const Date& rhs); +bool operator!=(const Date& lhs, const Date& rhs); +bool operator<(const Date& lhs, const Date& rhs); +bool operator<=(const Date& lhs, const Date& rhs); +bool operator>(const Date& lhs, const Date& rhs); +bool operator>=(const Date& lhs, const Date& rhs); +Date operator-(const Date& lhs, Date::Size rhs); +Date operator+(const Date& lhs, Date::Size rhs); //! utillities: -bool check(const Date &d); -inline bool -isLeapYear(Date::Size y); - - - +bool check(const Date& d); +inline bool isLeapYear(Date::Size y); //! check if the date object passed in is valid - inline bool - check(const Date &d) - { - if(d.month==0 || d.month >12) - return false; - else - { - //! month == 1 3 5 7 8 10 12 - if(d.month==1 || d.month==3 || d.month==5 || d.month==7 || - d.month==8 || d.month==10|| d.month==12) - { - if(d.day==0 || d.day > 31) return false; - else +inline bool check(const Date& d) +{ + if (d.month == 0 || d.month > 12) + return false; + else { + //! month == 1 3 5 7 8 10 12 + if (d.month == 1 || d.month == 3 || d.month == 5 || d.month == 7 || + d.month == 8 || d.month == 10 || d.month == 12) { + if (d.day == 0 || d.day > 31) + return false; + else return true; - } - else - { - //! month == 4 6 9 11 - if(d.month==4 || d.month==6 || d.month==9 || d.month==11) - { - if(d.day==0 || d.day > 30) return false; - else - return true; - } - else - { - //! month == 2 - if(isLeapYear(d.year)) - { - if(d.day==0 || d.day >29) return false; - else - return true; - } - else - { - if(d.day==0 || d.day >28) return false; - else - return true; - } - } - } - } - } - - inline bool - isLeapYear(Date::Size y) - { - if (!(y%400)) - { - return true; - } - else - { - if(!(y%100)) - { - return false; - } - else - return !(y%4); - } - } + } + else { + //! month == 4 6 9 11 + if (d.month == 4 || d.month == 6 || d.month == 9 || d.month == 11) { + if (d.day == 0 || d.day > 30) + return false; + else + return true; + } + else { + //! month == 2 + if (isLeapYear(d.year)) { + if (d.day == 0 || d.day > 29) + return false; + else + return true; + } + else { + if (d.day == 0 || d.day > 28) + return false; + else + return true; + } + } + } + } +} + +inline bool isLeapYear(Date::Size y) +{ + if (!(y % 400)) { + return true; + } + else { + if (!(y % 100)) { + return false; + } + else + return !(y % 4); + } +} #endif // DATE_H diff --git a/ch14/ex14_24_TEST.cpp b/ch14/ex14_24_TEST.cpp index 093f7bdd..dee433d8 100644 --- a/ch14/ex14_24_TEST.cpp +++ b/ch14/ex14_24_TEST.cpp @@ -7,18 +7,22 @@ ***************************************************************************/ //! //! Exercise 14.20: -//! Define the addition and compound-assignment operators for your Sales_data class. +//! Define the addition and compound-assignment operators for your Sales_data +//! class. //! //! Exercise 14.22: -//! Define a version of the assignment operator that can assign a string representing +//! Define a version of the assignment operator that can assign a string +//! representing //! an ISBN to a Sales_data. //! //! Exercise 14.23: -//! Define an initializer_list assignment operator for your version of the StrVec +//! Define an initializer_list assignment operator for your version of the +//! StrVec //! class. //! //! Exercise 14.24: -//! Decide whether the class you used in exercise 7.40 from § 7.5.1 (p. 291) needs a +//! Decide whether the class you used in exercise 7.40 from § 7.5.1 (p. 291) +//! needs a //! copy- and move-assignment operator. If so, define those operators. //! @@ -30,15 +34,7 @@ int main() Date lhs(9999999), rhs(1); - std::cout << (lhs -= 12000) <<"\n"; - + std::cout << (lhs -= 12000) << "\n"; return 0; } - - - - - - - diff --git a/ch14/ex14_26_StrBlob.cpp b/ch14/ex14_26_StrBlob.cpp index 5b081e69..24eef2d8 100644 --- a/ch14/ex14_26_StrBlob.cpp +++ b/ch14/ex14_26_StrBlob.cpp @@ -7,34 +7,35 @@ // //================================================================== -bool operator==(const StrBlob &lhs, const StrBlob &rhs) +bool operator==(const StrBlob& lhs, const StrBlob& rhs) { - return *lhs.data == *rhs.data; + return *lhs.data == *rhs.data; } -bool operator!=(const StrBlob &lhs, const StrBlob &rhs) +bool operator!=(const StrBlob& lhs, const StrBlob& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator< (const StrBlob &lhs, const StrBlob &rhs) +bool operator<(const StrBlob& lhs, const StrBlob& rhs) { - return std::lexicographical_compare(lhs.data->begin(), lhs.data->end(), rhs.data->begin(), rhs.data->end()); + return std::lexicographical_compare(lhs.data->begin(), lhs.data->end(), + rhs.data->begin(), rhs.data->end()); } -bool operator> (const StrBlob &lhs, const StrBlob &rhs) +bool operator>(const StrBlob& lhs, const StrBlob& rhs) { - return rhs < lhs; + return rhs < lhs; } -bool operator<=(const StrBlob &lhs, const StrBlob &rhs) +bool operator<=(const StrBlob& lhs, const StrBlob& rhs) { - return !(rhs < lhs); + return !(rhs < lhs); } -bool operator>=(const StrBlob &lhs, const StrBlob &rhs) +bool operator>=(const StrBlob& lhs, const StrBlob& rhs) { - return !(lhs < rhs); + return !(lhs < rhs); } //================================================================ @@ -43,34 +44,34 @@ bool operator>=(const StrBlob &lhs, const StrBlob &rhs) // //================================================================ -bool operator==(const StrBlobPtr &lhs, const StrBlobPtr &rhs) +bool operator==(const StrBlobPtr& lhs, const StrBlobPtr& rhs) { - return lhs.curr == rhs.curr; + return lhs.curr == rhs.curr; } -bool operator!=(const StrBlobPtr &lhs, const StrBlobPtr &rhs) +bool operator!=(const StrBlobPtr& lhs, const StrBlobPtr& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator< (const StrBlobPtr &x, const StrBlobPtr &y) +bool operator<(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr < y.curr; + return x.curr < y.curr; } -bool operator> (const StrBlobPtr &x, const StrBlobPtr &y) +bool operator>(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr > y.curr; + return x.curr > y.curr; } -bool operator<=(const StrBlobPtr &x, const StrBlobPtr &y) +bool operator<=(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr <= y.curr; + return x.curr <= y.curr; } -bool operator>=(const StrBlobPtr &x, const StrBlobPtr &y) +bool operator>=(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr >= y.curr; + return x.curr >= y.curr; } //================================================================ @@ -79,34 +80,34 @@ bool operator>=(const StrBlobPtr &x, const StrBlobPtr &y) // //================================================================ -bool operator==(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator==(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr == rhs.curr; + return lhs.curr == rhs.curr; } -bool operator!=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator!=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator< (const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator<(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr < rhs.curr; + return lhs.curr < rhs.curr; } -bool operator> (const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator>(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr > rhs.curr; + return lhs.curr > rhs.curr; } -bool operator<=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator<=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr <= rhs.curr; + return lhs.curr <= rhs.curr; } -bool operator>=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator>=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr >= rhs.curr; + return lhs.curr >= rhs.curr; } //================================================================== @@ -115,20 +116,20 @@ bool operator>=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) // //================================================================== -StrBlob& StrBlob::operator=(const StrBlob &lhs) +StrBlob& StrBlob::operator=(const StrBlob& lhs) { - data = make_shared>(*lhs.data); - return *this; + data = make_shared>(*lhs.data); + return *this; } -StrBlob& StrBlob::operator=(StrBlob &&rhs) NOEXCEPT +StrBlob& StrBlob::operator=(StrBlob&& rhs) NOEXCEPT { - if (this != &rhs) { - data = std::move(rhs.data); - rhs.data = nullptr; - } + if (this != &rhs) { + data = std::move(rhs.data); + rhs.data = nullptr; + } - return *this; + return *this; } //================================================================== @@ -139,12 +140,12 @@ StrBlob& StrBlob::operator=(StrBlob &&rhs) NOEXCEPT StrBlobPtr StrBlob::begin() { - return StrBlobPtr(*this); + return StrBlobPtr(*this); } StrBlobPtr StrBlob::end() { - return StrBlobPtr(*this, data->size()); + return StrBlobPtr(*this, data->size()); } ConstStrBlobPtr StrBlob::cbegin() const diff --git a/ch14/ex14_26_StrBlob.h b/ch14/ex14_26_StrBlob.h index de008fba..35e4114b 100644 --- a/ch14/ex14_26_StrBlob.h +++ b/ch14/ex14_26_StrBlob.h @@ -24,7 +24,8 @@ using std::string; using std::initializer_list; #include -using std::make_shared; using std::shared_ptr; +using std::make_shared; +using std::shared_ptr; #include @@ -44,28 +45,30 @@ class ConstStrBlobPtr; //================================================================================= class StrBlob { - using size_type = vector::size_type; - friend class ConstStrBlobPtr; - friend class StrBlobPtr; - friend bool operator==(const StrBlob&, const StrBlob&); - friend bool operator!=(const StrBlob&, const StrBlob&); - friend bool operator< (const StrBlob&, const StrBlob&); - friend bool operator> (const StrBlob&, const StrBlob&); - friend bool operator<=(const StrBlob&, const StrBlob&); - friend bool operator>=(const StrBlob&, const StrBlob&); + using size_type = vector::size_type; + friend class ConstStrBlobPtr; + friend class StrBlobPtr; + friend bool operator==(const StrBlob&, const StrBlob&); + friend bool operator!=(const StrBlob&, const StrBlob&); + friend bool operator<(const StrBlob&, const StrBlob&); + friend bool operator>(const StrBlob&, const StrBlob&); + friend bool operator<=(const StrBlob&, const StrBlob&); + friend bool operator>=(const StrBlob&, const StrBlob&); public: - StrBlob() : data(make_shared>()) {} - StrBlob(initializer_list il) : data(make_shared>(il)) {} + StrBlob() : data(make_shared>()) {} + StrBlob(initializer_list il) : data(make_shared>(il)) + { + } - StrBlob(const StrBlob &sb) : data(make_shared>(*sb.data)) {} - StrBlob& operator=(const StrBlob&); + StrBlob(const StrBlob& sb) : data(make_shared>(*sb.data)) {} + StrBlob& operator=(const StrBlob&); - StrBlob(StrBlob &&rhs) NOEXCEPT : data(std::move(rhs.data)) {} - StrBlob& operator=(StrBlob &&) NOEXCEPT; + StrBlob(StrBlob&& rhs) NOEXCEPT : data(std::move(rhs.data)) {} + StrBlob& operator=(StrBlob&&) NOEXCEPT; - StrBlobPtr begin(); - StrBlobPtr end(); + StrBlobPtr begin(); + StrBlobPtr end(); ConstStrBlobPtr cbegin() const; ConstStrBlobPtr cend() const; @@ -76,61 +79,61 @@ class StrBlob { size_type size() const { return data->size(); } bool empty() const { return data->empty(); } - void push_back(const string &t) { data->push_back(t); } - void push_back(string &&s) { data->push_back(std::move(s)); } + void push_back(const string& t) { data->push_back(t); } + void push_back(string&& s) { data->push_back(std::move(s)); } - void pop_back(); - string& front(); - string& back(); - const string& front() const; - const string& back() const; + void pop_back(); + string& front(); + string& back(); + const string& front() const; + const string& back() const; private: - void check(size_type, const string&) const; + void check(size_type, const string&) const; shared_ptr> data; }; bool operator==(const StrBlob&, const StrBlob&); bool operator!=(const StrBlob&, const StrBlob&); -bool operator< (const StrBlob&, const StrBlob&); -bool operator> (const StrBlob&, const StrBlob&); +bool operator<(const StrBlob&, const StrBlob&); +bool operator>(const StrBlob&, const StrBlob&); bool operator<=(const StrBlob&, const StrBlob&); bool operator>=(const StrBlob&, const StrBlob&); inline void StrBlob::pop_back() { - check(0, "pop_back on empty StrBlob"); - data->pop_back(); + check(0, "pop_back on empty StrBlob"); + data->pop_back(); } inline string& StrBlob::front() { - check(0, "front on empty StrBlob"); - return data->front(); + check(0, "front on empty StrBlob"); + return data->front(); } inline string& StrBlob::back() { - check(0, "back on empty StrBlob"); - return data->back(); + check(0, "back on empty StrBlob"); + return data->back(); } inline const string& StrBlob::front() const { - check(0, "front on empty StrBlob"); - return data->front(); + check(0, "front on empty StrBlob"); + return data->front(); } inline const string& StrBlob::back() const { - check(0, "back on empty StrBlob"); - return data->back(); + check(0, "back on empty StrBlob"); + return data->back(); } -inline void StrBlob::check(size_type i, const string &msg) const +inline void StrBlob::check(size_type i, const string& msg) const { - if (i >= data->size()) throw std::out_of_range(msg); + if (i >= data->size()) throw std::out_of_range(msg); } inline string& StrBlob::operator[](size_t n) @@ -152,56 +155,57 @@ inline const string& StrBlob::operator[](size_t n) const //================================================================================= class StrBlobPtr { - friend bool operator==(const StrBlobPtr&, const StrBlobPtr&); - friend bool operator!=(const StrBlobPtr&, const StrBlobPtr&); - friend bool operator< (const StrBlobPtr&, const StrBlobPtr&); - friend bool operator> (const StrBlobPtr&, const StrBlobPtr&); - friend bool operator<=(const StrBlobPtr&, const StrBlobPtr&); - friend bool operator>=(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator==(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator!=(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator<(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator>(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator<=(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator>=(const StrBlobPtr&, const StrBlobPtr&); public: - StrBlobPtr() : curr(0) {} - StrBlobPtr(StrBlob &s, size_t sz = 0) : wptr(s.data), curr(sz) {} + StrBlobPtr() : curr(0) {} + StrBlobPtr(StrBlob& s, size_t sz = 0) : wptr(s.data), curr(sz) {} - string& deref() const; - StrBlobPtr& incr(); + string& deref() const; + StrBlobPtr& incr(); string& operator[](size_t n); const string& operator[](size_t n) const; private: - shared_ptr> check(size_t, const string&) const; + shared_ptr> check(size_t, const string&) const; - std::weak_ptr> wptr; - size_t curr; + std::weak_ptr> wptr; + size_t curr; }; bool operator==(const StrBlobPtr&, const StrBlobPtr&); bool operator!=(const StrBlobPtr&, const StrBlobPtr&); -bool operator< (const StrBlobPtr&, const StrBlobPtr&); -bool operator> (const StrBlobPtr&, const StrBlobPtr&); +bool operator<(const StrBlobPtr&, const StrBlobPtr&); +bool operator>(const StrBlobPtr&, const StrBlobPtr&); bool operator<=(const StrBlobPtr&, const StrBlobPtr&); bool operator>=(const StrBlobPtr&, const StrBlobPtr&); inline string& StrBlobPtr::deref() const { - auto p = check(curr, "dereference past end"); - return (*p)[curr]; + auto p = check(curr, "dereference past end"); + return (*p)[curr]; } inline StrBlobPtr& StrBlobPtr::incr() { - check(curr, "increment past end of StrBlobPtr"); - ++curr; - return *this; + check(curr, "increment past end of StrBlobPtr"); + ++curr; + return *this; } -inline shared_ptr> StrBlobPtr::check(size_t i, const string &msg) const +inline shared_ptr> StrBlobPtr::check(size_t i, + const string& msg) const { - auto ret = wptr.lock(); - if (!ret) throw std::runtime_error("unbound StrBlobPtr"); - if (i >= ret->size()) throw std::out_of_range(msg); - return ret; + auto ret = wptr.lock(); + if (!ret) throw std::runtime_error("unbound StrBlobPtr"); + if (i >= ret->size()) throw std::out_of_range(msg); + return ret; } inline string& StrBlobPtr::operator[](size_t n) @@ -223,24 +227,24 @@ inline const string& StrBlobPtr::operator[](size_t n) const //================================================================================= class ConstStrBlobPtr { - friend bool operator==(const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator!=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator< (const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator> (const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator<=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator>=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator==(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator!=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator<(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator>(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator<=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator>=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); public: - ConstStrBlobPtr() : curr(0) {} - ConstStrBlobPtr(const StrBlob &s, size_t sz = 0) : wptr(s.data), curr(sz) {} + ConstStrBlobPtr() : curr(0) {} + ConstStrBlobPtr(const StrBlob& s, size_t sz = 0) : wptr(s.data), curr(sz) {} - const string& deref() const; - ConstStrBlobPtr& incr(); + const string& deref() const; + ConstStrBlobPtr& incr(); const string& operator[](size_t n) const; private: - std::shared_ptr> check(size_t, const string&) const; + std::shared_ptr> check(size_t, const string&) const; std::weak_ptr> wptr; size_t curr; @@ -248,30 +252,31 @@ class ConstStrBlobPtr { bool operator==(const ConstStrBlobPtr&, const ConstStrBlobPtr&); bool operator!=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); -bool operator< (const ConstStrBlobPtr&, const ConstStrBlobPtr&); -bool operator> (const ConstStrBlobPtr&, const ConstStrBlobPtr&); +bool operator<(const ConstStrBlobPtr&, const ConstStrBlobPtr&); +bool operator>(const ConstStrBlobPtr&, const ConstStrBlobPtr&); bool operator<=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); bool operator>=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); inline const string& ConstStrBlobPtr::deref() const { - auto p = check(curr, "dereference past end"); - return (*p)[curr]; + auto p = check(curr, "dereference past end"); + return (*p)[curr]; } inline ConstStrBlobPtr& ConstStrBlobPtr::incr() { - check(curr, "increment past end of StrBlobPtr"); - ++curr; - return *this; + check(curr, "increment past end of StrBlobPtr"); + ++curr; + return *this; } -inline std::shared_ptr> ConstStrBlobPtr::check(size_t i, const string &msg) const +inline std::shared_ptr> +ConstStrBlobPtr::check(size_t i, const string& msg) const { - auto ret = wptr.lock(); - if (!ret) throw std::runtime_error("unbound StrBlobPtr"); - if (i >= ret->size()) throw std::out_of_range(msg); - return ret; + auto ret = wptr.lock(); + if (!ret) throw std::runtime_error("unbound StrBlobPtr"); + if (i >= ret->size()) throw std::out_of_range(msg); + return ret; } inline const string& ConstStrBlobPtr::operator[](size_t n) const @@ -280,4 +285,4 @@ inline const string& ConstStrBlobPtr::operator[](size_t n) const return (*p)[n]; } -#endif //CP5_STRBLOB_H_ +#endif // CP5_STRBLOB_H_ diff --git a/ch14/ex14_26_StrBlobTest.cpp b/ch14/ex14_26_StrBlobTest.cpp index 4fd5513c..f3b01fc8 100644 --- a/ch14/ex14_26_StrBlobTest.cpp +++ b/ch14/ex14_26_StrBlobTest.cpp @@ -3,16 +3,17 @@ int main() { - StrBlob sb1{ "a", "b", "c" }; + StrBlob sb1{"a", "b", "c"}; StrBlob sb2 = sb1; sb2[2] = "b"; - if (sb1 > sb2) { - for (ConstStrBlobPtr iter = sb1.cbegin(); iter < sb1.cend(); iter.incr()) - std::cout << iter.deref() << " "; - std::cout << std::endl; - } + if (sb1 > sb2) { + for (ConstStrBlobPtr iter = sb1.cbegin(); iter < sb1.cend(); + iter.incr()) + std::cout << iter.deref() << " "; + std::cout << std::endl; + } StrBlobPtr iter(sb2); std::cout << iter[2] << std::endl; diff --git a/ch14/ex14_26_StrVec.cpp b/ch14/ex14_26_StrVec.cpp index 690f7c30..44ceed43 100644 --- a/ch14/ex14_26_StrVec.cpp +++ b/ch14/ex14_26_StrVec.cpp @@ -1,145 +1,149 @@ #include "ex14_26_StrVec.h" #include // for_each, equal -void StrVec::push_back(const std::string &s) +void StrVec::push_back(const std::string& s) { - chk_n_alloc(); - alloc.construct(first_free++, s); + chk_n_alloc(); + alloc.construct(first_free++, s); } -std::pair -StrVec::alloc_n_copy(const std::string *b, const std::string *e) +std::pair StrVec::alloc_n_copy(const std::string* b, + const std::string* e) { - auto data = alloc.allocate(e-b); - return { data, std::uninitialized_copy(b, e, data) }; + auto data = alloc.allocate(e - b); + return {data, std::uninitialized_copy(b, e, data)}; } void StrVec::free() { - if (elements) { - for_each(elements, first_free, [this](std::string &rhs){ alloc.destroy(&rhs); }); - alloc.deallocate(elements, cap - elements); - } + if (elements) { + for_each(elements, first_free, + [this](std::string& rhs) { alloc.destroy(&rhs); }); + alloc.deallocate(elements, cap - elements); + } } -void StrVec::range_initialize(const std::string *first, const std::string *last) +void StrVec::range_initialize(const std::string* first, const std::string* last) { - auto newdata = alloc_n_copy(first, last); - elements = newdata.first; - first_free = cap = newdata.second; + auto newdata = alloc_n_copy(first, last); + elements = newdata.first; + first_free = cap = newdata.second; } -StrVec::StrVec(const StrVec &rhs) +StrVec::StrVec(const StrVec& rhs) { - range_initialize(rhs.begin(), rhs.end()); + range_initialize(rhs.begin(), rhs.end()); } StrVec::StrVec(std::initializer_list il) { - range_initialize(il.begin(), il.end()); + range_initialize(il.begin(), il.end()); } StrVec::~StrVec() { - free(); + free(); } -StrVec& StrVec::operator = (const StrVec &rhs) +StrVec& StrVec::operator=(const StrVec& rhs) { - auto data = alloc_n_copy(rhs.begin(), rhs.end()); - free(); - elements = data.first; - first_free = cap = data.second; - return *this; + auto data = alloc_n_copy(rhs.begin(), rhs.end()); + free(); + elements = data.first; + first_free = cap = data.second; + return *this; } void StrVec::alloc_n_move(size_t new_cap) { - auto newdata = alloc.allocate(new_cap); - auto dest = newdata; - auto elem = elements; - for (size_t i = 0; i != size(); ++i) - alloc.construct(dest++, std::move(*elem++)); - free(); - elements = newdata; - first_free = dest; - cap = elements + new_cap; + auto newdata = alloc.allocate(new_cap); + auto dest = newdata; + auto elem = elements; + for (size_t i = 0; i != size(); ++i) + alloc.construct(dest++, std::move(*elem++)); + free(); + elements = newdata; + first_free = dest; + cap = elements + new_cap; } void StrVec::reallocate() { - auto newcapacity = size() ? 2 * size() : 1; - alloc_n_move(newcapacity); + auto newcapacity = size() ? 2 * size() : 1; + alloc_n_move(newcapacity); } void StrVec::reserve(size_t new_cap) { - if (new_cap <= capacity()) return; - alloc_n_move(new_cap); + if (new_cap <= capacity()) return; + alloc_n_move(new_cap); } void StrVec::resize(size_t count) { - resize(count, std::string()); + resize(count, std::string()); } -void StrVec::resize(size_t count, const std::string &s) +void StrVec::resize(size_t count, const std::string& s) { - if (count > size()) { - if (count > capacity()) reserve(count * 2); - for (size_t i = size(); i != count; ++i) - alloc.construct(first_free++, s); - } - else if (count < size()) { - while (first_free != elements + count) - alloc.destroy(--first_free); - } + if (count > size()) { + if (count > capacity()) reserve(count * 2); + for (size_t i = size(); i != count; ++i) + alloc.construct(first_free++, s); + } + else if (count < size()) { + while (first_free != elements + count) alloc.destroy(--first_free); + } } -StrVec::StrVec(StrVec &&s) NOEXCEPT : elements(s.elements), first_free(s.first_free), cap(s.cap) +StrVec::StrVec(StrVec&& s) NOEXCEPT : elements(s.elements), + first_free(s.first_free), + cap(s.cap) { - // leave s in a state in which it is safe to run the destructor. - s.elements = s.first_free = s.cap = nullptr; + // leave s in a state in which it is safe to run the destructor. + s.elements = s.first_free = s.cap = nullptr; } -StrVec& StrVec::operator = (StrVec &&rhs) NOEXCEPT +StrVec& StrVec::operator=(StrVec&& rhs) NOEXCEPT { - if (this != &rhs) { - free(); - elements = rhs.elements; - first_free = rhs.first_free; - cap = rhs.cap; - rhs.elements = rhs.first_free = rhs.cap = nullptr; - } - return *this; + if (this != &rhs) { + free(); + elements = rhs.elements; + first_free = rhs.first_free; + cap = rhs.cap; + rhs.elements = rhs.first_free = rhs.cap = nullptr; + } + return *this; } -bool operator==(const StrVec &lhs, const StrVec &rhs) +bool operator==(const StrVec& lhs, const StrVec& rhs) { - return (lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin())); + return (lhs.size() == rhs.size() && + std::equal(lhs.begin(), lhs.end(), rhs.begin())); } -bool operator!=(const StrVec &lhs, const StrVec &rhs) +bool operator!=(const StrVec& lhs, const StrVec& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator<(const StrVec &lhs, const StrVec &rhs) +bool operator<(const StrVec& lhs, const StrVec& rhs) { - return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); + return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), + rhs.end()); } -bool operator>(const StrVec &lhs, const StrVec &rhs) +bool operator>(const StrVec& lhs, const StrVec& rhs) { - return rhs < lhs; + return rhs < lhs; } -bool operator<=(const StrVec &lhs, const StrVec &rhs) +bool operator<=(const StrVec& lhs, const StrVec& rhs) { - return !(rhs < lhs); + return !(rhs < lhs); } -bool operator>=(const StrVec &lhs, const StrVec &rhs) +bool operator>=(const StrVec& lhs, const StrVec& rhs) { - return !(lhs < rhs); + return !(lhs < rhs); } diff --git a/ch14/ex14_26_StrVec.h b/ch14/ex14_26_StrVec.h index 3ab9d78f..48569104 100644 --- a/ch14/ex14_26_StrVec.h +++ b/ch14/ex14_26_StrVec.h @@ -11,59 +11,62 @@ #define NOEXCEPT #endif -class StrVec -{ - friend bool operator==(const StrVec&, const StrVec&); - friend bool operator!=(const StrVec&, const StrVec&); - friend bool operator< (const StrVec&, const StrVec&); - friend bool operator> (const StrVec&, const StrVec&); - friend bool operator<=(const StrVec&, const StrVec&); - friend bool operator>=(const StrVec&, const StrVec&); +class StrVec { + friend bool operator==(const StrVec&, const StrVec&); + friend bool operator!=(const StrVec&, const StrVec&); + friend bool operator<(const StrVec&, const StrVec&); + friend bool operator>(const StrVec&, const StrVec&); + friend bool operator<=(const StrVec&, const StrVec&); + friend bool operator>=(const StrVec&, const StrVec&); public: - StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} - StrVec(std::initializer_list); - StrVec(const StrVec&); - StrVec& operator=(const StrVec&); - StrVec(StrVec&&) NOEXCEPT; - StrVec& operator=(StrVec&&) NOEXCEPT; - ~StrVec(); + StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {} + StrVec(std::initializer_list); + StrVec(const StrVec&); + StrVec& operator=(const StrVec&); + StrVec(StrVec&&) NOEXCEPT; + StrVec& operator=(StrVec&&) NOEXCEPT; + ~StrVec(); - void push_back(const std::string&); - size_t size() const { return first_free - elements; } - size_t capacity() const { return cap - elements; } - std::string *begin() const { return elements; } - std::string *end() const { return first_free; } + void push_back(const std::string&); + size_t size() const { return first_free - elements; } + size_t capacity() const { return cap - elements; } + std::string* begin() const { return elements; } + std::string* end() const { return first_free; } - std::string& at(size_t pos) { return *(elements + pos); } - const std::string& at(size_t pos) const { return *(elements + pos); } + std::string& at(size_t pos) { return *(elements + pos); } + const std::string& at(size_t pos) const { return *(elements + pos); } std::string& operator[](size_t n) { return elements[n]; } const std::string& operator[](size_t n) const { return elements[n]; } - void reserve(size_t new_cap); - void resize(size_t count); - void resize(size_t count, const std::string&); + void reserve(size_t new_cap); + void resize(size_t count); + void resize(size_t count, const std::string&); private: - std::pair alloc_n_copy(const std::string*, const std::string*); - void free(); - void chk_n_alloc() { if (size() == capacity()) reallocate(); } - void reallocate(); - void alloc_n_move(size_t new_cap); - void range_initialize(const std::string*, const std::string*); + std::pair alloc_n_copy(const std::string*, + const std::string*); + void free(); + void chk_n_alloc() + { + if (size() == capacity()) reallocate(); + } + void reallocate(); + void alloc_n_move(size_t new_cap); + void range_initialize(const std::string*, const std::string*); private: - std::string *elements; - std::string *first_free; - std::string *cap; - std::allocator alloc; + std::string* elements; + std::string* first_free; + std::string* cap; + std::allocator alloc; }; bool operator==(const StrVec&, const StrVec&); bool operator!=(const StrVec&, const StrVec&); -bool operator< (const StrVec&, const StrVec&); -bool operator> (const StrVec&, const StrVec&); +bool operator<(const StrVec&, const StrVec&); +bool operator>(const StrVec&, const StrVec&); bool operator<=(const StrVec&, const StrVec&); bool operator>=(const StrVec&, const StrVec&); diff --git a/ch14/ex14_26_StrVecMain.cpp b/ch14/ex14_26_StrVecMain.cpp index ff2e5fd7..7af9ae1a 100644 --- a/ch14/ex14_26_StrVecMain.cpp +++ b/ch14/ex14_26_StrVecMain.cpp @@ -4,45 +4,44 @@ int main() { - StrVec vec; - vec.reserve(6); - std::cout << "capacity(reserve to 6): " << vec.capacity() << std::endl; + StrVec vec; + vec.reserve(6); + std::cout << "capacity(reserve to 6): " << vec.capacity() << std::endl; - vec.reserve(4); - std::cout << "capacity(reserve to 4): " << vec.capacity() << std::endl; + vec.reserve(4); + std::cout << "capacity(reserve to 4): " << vec.capacity() << std::endl; - vec.push_back("hello"); - vec.push_back("world"); + vec.push_back("hello"); + vec.push_back("world"); - vec.resize(4); + vec.resize(4); - for (auto i = vec.begin(); i != vec.end(); ++i) - std::cout << *i << std::endl; - std::cout << "-EOF-" << std::endl; + for (auto i = vec.begin(); i != vec.end(); ++i) + std::cout << *i << std::endl; + std::cout << "-EOF-" << std::endl; - vec.resize(1); + vec.resize(1); - for (auto i = vec.begin(); i != vec.end(); ++i) - std::cout << *i << std::endl; - std::cout << "-EOF-" << std::endl; + for (auto i = vec.begin(); i != vec.end(); ++i) + std::cout << *i << std::endl; + std::cout << "-EOF-" << std::endl; - StrVec vec_list{"hello", "world", "pezy"}; + StrVec vec_list{"hello", "world", "pezy"}; - for (auto i = vec_list.begin(); i != vec_list.end(); ++i) - std::cout << *i << " "; - std::cout << std::endl; + for (auto i = vec_list.begin(); i != vec_list.end(); ++i) + std::cout << *i << " "; + std::cout << std::endl; - // Test operator== + // Test operator== - const StrVec const_vec_list{ "hello", "world", "pezy" }; - if (vec_list == const_vec_list) - for (const auto &str : const_vec_list) - std::cout << str << " "; - std::cout << std::endl; + const StrVec const_vec_list{"hello", "world", "pezy"}; + if (vec_list == const_vec_list) + for (const auto& str : const_vec_list) std::cout << str << " "; + std::cout << std::endl; - // Test operator< - const StrVec const_vec_list_small{"hello", "pezy", "ok"}; - std::cout << (const_vec_list_small < const_vec_list) << std::endl; + // Test operator< + const StrVec const_vec_list_small{"hello", "pezy", "ok"}; + std::cout << (const_vec_list_small < const_vec_list) << std::endl; // Test [] std::cout << const_vec_list_small[1] << std::endl; diff --git a/ch14/ex14_26_String.cpp b/ch14/ex14_26_String.cpp index 5d7c8cf3..505add78 100644 --- a/ch14/ex14_26_String.cpp +++ b/ch14/ex14_26_String.cpp @@ -7,48 +7,50 @@ // //=========================================================================== -std::ostream& operator<<(std::ostream &os, const String &lhs) +std::ostream& operator<<(std::ostream& os, const String& lhs) { - os << lhs.c_str(); - return os; + os << lhs.c_str(); + return os; } -std::istream& operator>>(std::istream &is, String &rhs) +std::istream& operator>>(std::istream& is, String& rhs) { - for (char c; (c = is.get()) != '\n'; ) { - rhs.push_back(c); - } - return is; + for (char c; (c = is.get()) != '\n';) { + rhs.push_back(c); + } + return is; } -bool operator==(const String &lhs, const String &rhs) +bool operator==(const String& lhs, const String& rhs) { - return (lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin())); + return (lhs.size() == rhs.size() && + std::equal(lhs.begin(), lhs.end(), rhs.begin())); } -bool operator!=(const String &lhs, const String &rhs) +bool operator!=(const String& lhs, const String& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator<(const String &lhs, const String &rhs) +bool operator<(const String& lhs, const String& rhs) { - return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); + return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), + rhs.end()); } -bool operator>(const String &lhs, const String &rhs) +bool operator>(const String& lhs, const String& rhs) { - return rhs < lhs; + return rhs < lhs; } -bool operator<=(const String &lhs, const String &rhs) +bool operator<=(const String& lhs, const String& rhs) { - return !(rhs < lhs); + return !(rhs < lhs); } -bool operator>=(const String &lhs, const String &rhs) +bool operator>=(const String& lhs, const String& rhs) { - return !(lhs < rhs); + return !(lhs < rhs); } //=========================================================================== @@ -57,12 +59,11 @@ bool operator>=(const String &lhs, const String &rhs) // //=========================================================================== -String::String(const char *s) +String::String(const char* s) { - char *sl = const_cast(s); - while (*sl) - ++sl; - range_initializer(s, ++sl); + char* sl = const_cast(s); + while (*sl) ++sl; + range_initializer(s, ++sl); } //=========================================================================== @@ -73,40 +74,43 @@ String::String(const char *s) String::String(const String& rhs) { - range_initializer(rhs.elements, rhs.first_free); + range_initializer(rhs.elements, rhs.first_free); } -String& String::operator = (const String &rhs) +String& String::operator=(const String& rhs) { - auto newstr = alloc_n_copy(rhs.elements, rhs.first_free); - free(); - elements = newstr.first; - first_free = cap = newstr.second; - last_elem = first_free - 1; - return *this; + auto newstr = alloc_n_copy(rhs.elements, rhs.first_free); + free(); + elements = newstr.first; + first_free = cap = newstr.second; + last_elem = first_free - 1; + return *this; } -String::String(String &&s) NOEXCEPT : elements(s.elements), last_elem(s.last_elem), first_free(s.first_free), cap(s.cap) +String::String(String&& s) NOEXCEPT : elements(s.elements), + last_elem(s.last_elem), + first_free(s.first_free), + cap(s.cap) { - s.elements = s.last_elem = s.first_free = s.cap = nullptr; + s.elements = s.last_elem = s.first_free = s.cap = nullptr; } -String& String::operator = (String &&rhs) NOEXCEPT +String& String::operator=(String&& rhs) NOEXCEPT { - if (this != &rhs) { - free(); - elements = rhs.elements; - last_elem = rhs.last_elem; - first_free = rhs.first_free; - cap = rhs.cap; - rhs.elements = rhs.last_elem = rhs.first_free = rhs.cap = nullptr; - } - return *this; + if (this != &rhs) { + free(); + elements = rhs.elements; + last_elem = rhs.last_elem; + first_free = rhs.first_free; + cap = rhs.cap; + rhs.elements = rhs.last_elem = rhs.first_free = rhs.cap = nullptr; + } + return *this; } String::~String() { - free(); + free(); } //=========================================================================== @@ -117,86 +121,85 @@ String::~String() void String::push_back(const char c) { - chk_n_alloc(); - *last_elem = c; - last_elem = first_free; - alloc.construct(first_free++, '\0'); + chk_n_alloc(); + *last_elem = c; + last_elem = first_free; + alloc.construct(first_free++, '\0'); } void String::reallocate() { - // \0 | - - // ^ ^ - // elements first_free - // last_elem cap + // \0 | - + // ^ ^ + // elements first_free + // last_elem cap - auto newcapacity = size() ? 2 * (size() + 1) : 2; - alloc_n_move(newcapacity); + auto newcapacity = size() ? 2 * (size() + 1) : 2; + alloc_n_move(newcapacity); } void String::alloc_n_move(size_t new_cap) { - auto newdata = alloc.allocate(new_cap); - auto dest = newdata; - auto elem = elements; - for (size_t i = 0; i != size() + 1; ++i) - alloc.construct(dest++, std::move(*elem++)); - free(); - elements = newdata; - last_elem = dest - 1; - first_free = dest; - cap = elements + new_cap; + auto newdata = alloc.allocate(new_cap); + auto dest = newdata; + auto elem = elements; + for (size_t i = 0; i != size() + 1; ++i) + alloc.construct(dest++, std::move(*elem++)); + free(); + elements = newdata; + last_elem = dest - 1; + first_free = dest; + cap = elements + new_cap; } void String::free() { - if (elements) { - std::for_each(elements, first_free, [this](char &c){ alloc.destroy(&c); }); - alloc.deallocate(elements, cap - elements); - } + if (elements) { + std::for_each(elements, first_free, + [this](char& c) { alloc.destroy(&c); }); + alloc.deallocate(elements, cap - elements); + } } -std::pair -String::alloc_n_copy(const char *b, const char *e) +std::pair String::alloc_n_copy(const char* b, const char* e) { - auto str = alloc.allocate(e-b); - return{ str, std::uninitialized_copy(b, e, str)}; + auto str = alloc.allocate(e - b); + return {str, std::uninitialized_copy(b, e, str)}; } -void String::range_initializer(const char *first, const char *last) +void String::range_initializer(const char* first, const char* last) { - auto newstr = alloc_n_copy(first, last); - elements = newstr.first; - first_free = cap = newstr.second; - last_elem = first_free - 1; + auto newstr = alloc_n_copy(first, last); + elements = newstr.first; + first_free = cap = newstr.second; + last_elem = first_free - 1; } void String::reserve(size_t new_cap) { - if (new_cap <= capacity()) return; - alloc_n_move(new_cap); + if (new_cap <= capacity()) return; + alloc_n_move(new_cap); } void String::resize(size_t count, char c) { - if (count > size()) { - if (count > capacity()) reserve(count * 2); - for (size_t i = size(); i != count; ++i) { - *last_elem++ = c; - alloc.construct(first_free++, '\0'); - } - - } - else if (count < size()) { - while (last_elem != elements + count) { - --last_elem; - alloc.destroy(--first_free); - } - *last_elem = '\0'; - } + if (count > size()) { + if (count > capacity()) reserve(count * 2); + for (size_t i = size(); i != count; ++i) { + *last_elem++ = c; + alloc.construct(first_free++, '\0'); + } + } + else if (count < size()) { + while (last_elem != elements + count) { + --last_elem; + alloc.destroy(--first_free); + } + *last_elem = '\0'; + } } void String::resize(size_t count) { - resize(count, ' '); + resize(count, ' '); } diff --git a/ch14/ex14_26_String.h b/ch14/ex14_26_String.h index 417115c5..970a0fd9 100644 --- a/ch14/ex14_26_String.h +++ b/ch14/ex14_26_String.h @@ -18,65 +18,67 @@ // //=================================================================================== -class String -{ - friend std::ostream& operator<<(std::ostream&, const String&); - friend std::istream& operator>>(std::istream&, String&); - friend bool operator==(const String&, const String&); - friend bool operator!=(const String&, const String&); - friend bool operator< (const String&, const String&); - friend bool operator> (const String&, const String&); - friend bool operator<=(const String&, const String&); - friend bool operator>=(const String&, const String&); +class String { + friend std::ostream& operator<<(std::ostream&, const String&); + friend std::istream& operator>>(std::istream&, String&); + friend bool operator==(const String&, const String&); + friend bool operator!=(const String&, const String&); + friend bool operator<(const String&, const String&); + friend bool operator>(const String&, const String&); + friend bool operator<=(const String&, const String&); + friend bool operator>=(const String&, const String&); public: - String() : String("") {} - String(const char *); - String(const String&); - String& operator=(const String&); - String(String &&) NOEXCEPT; - String& operator=(String&&) NOEXCEPT; - ~String(); + String() : String("") {} + String(const char*); + String(const String&); + String& operator=(const String&); + String(String&&) NOEXCEPT; + String& operator=(String&&) NOEXCEPT; + ~String(); - void push_back(const char); + void push_back(const char); - char* begin() const { return elements; } - char* end() const { return last_elem; } + char* begin() const { return elements; } + char* end() const { return last_elem; } char& operator[](size_t n) { return elements[n]; } const char& operator[](size_t n) const { return elements[n]; } - const char *c_str() const { return elements; } - size_t size() const { return last_elem - elements; } - size_t length() const { return size(); } - size_t capacity() const { return cap - elements; } + const char* c_str() const { return elements; } + size_t size() const { return last_elem - elements; } + size_t length() const { return size(); } + size_t capacity() const { return cap - elements; } - void reserve(size_t); - void resize(size_t); - void resize(size_t, char); + void reserve(size_t); + void resize(size_t); + void resize(size_t, char); private: - std::pair alloc_n_copy(const char*, const char*); - void range_initializer(const char*, const char*); - void free(); - void reallocate(); - void alloc_n_move(size_t new_cap); - void chk_n_alloc() { if (first_free == cap) reallocate(); } + std::pair alloc_n_copy(const char*, const char*); + void range_initializer(const char*, const char*); + void free(); + void reallocate(); + void alloc_n_move(size_t new_cap); + void chk_n_alloc() + { + if (first_free == cap) reallocate(); + } private: - char *elements; - char *last_elem; - char *first_free; - char *cap; - std::allocator alloc; + char* elements; + char* last_elem; + char* first_free; + char* cap; + std::allocator alloc; }; std::ostream& operator<<(std::ostream&, const String&); std::istream& operator>>(std::istream&, String&); bool operator==(const String&, const String&); bool operator!=(const String&, const String&); -bool operator< (const String&, const String&); -bool operator> (const String&, const String&); +bool operator<(const String&, const String&); +bool operator>(const String&, const String&); bool operator<=(const String&, const String&); bool operator>=(const String&, const String&); diff --git a/ch14/ex14_26_StringMain.cpp b/ch14/ex14_26_StringMain.cpp index 5371679c..2f590c9d 100644 --- a/ch14/ex14_26_StringMain.cpp +++ b/ch14/ex14_26_StringMain.cpp @@ -7,60 +7,58 @@ void foo(String x) { - std::cout << x << std::endl; + std::cout << x << std::endl; } void bar(const String& x) { - std::cout << x.c_str() << std::endl; + std::cout << x.c_str() << std::endl; } String baz() { - String ret("world"); - return ret; + String ret("world"); + return ret; } int main() { - char text[] = "world"; + char text[] = "world"; - String s0; - String s1("hello"); - String s2(std::move(s0)); - String s3 = s1; - String s4(text); - s2 = s1; + String s0; + String s1("hello"); + String s2(std::move(s0)); + String s3 = s1; + String s4(text); + s2 = s1; - if (s2 == s1) - std::cout << "s2 == s1" << std::endl; + if (s2 == s1) std::cout << "s2 == s1" << std::endl; - foo(s1); - bar(s1); - foo("temporary"); - bar("temporary"); - String s5 = baz(); + foo(s1); + bar(s1); + foo("temporary"); + bar("temporary"); + String s5 = baz(); - std::vector svec; - //svec.push_back(s0); - svec.push_back(s1); - svec.push_back(s2); - svec.push_back(s3); - svec.push_back(s4); - svec.push_back(baz()); - svec.push_back("good job"); + std::vector svec; + // svec.push_back(s0); + svec.push_back(s1); + svec.push_back(s2); + svec.push_back(s3); + svec.push_back(s4); + svec.push_back(baz()); + svec.push_back("good job"); - for (const auto &s : svec) { - std::cout << s << std::endl; - } + for (const auto& s : svec) { + std::cout << s << std::endl; + } - std::cout << "Input a string: "; - String s6; - std::cin >> s6; - std::cout << s6 << std::endl; + std::cout << "Input a string: "; + String s6; + std::cin >> s6; + std::cout << s6 << std::endl; - if (s6 > s1) - std::cout << "s6 > s1" << std::endl; + if (s6 > s1) std::cout << "s6 > s1" << std::endl; std::cout << s5[2] << std::endl; } diff --git a/ch14/ex14_27_28_StrBlob.cpp b/ch14/ex14_27_28_StrBlob.cpp index 522b6258..621bd07e 100644 --- a/ch14/ex14_27_28_StrBlob.cpp +++ b/ch14/ex14_27_28_StrBlob.cpp @@ -7,34 +7,35 @@ // //================================================================== -bool operator==(const StrBlob &lhs, const StrBlob &rhs) +bool operator==(const StrBlob& lhs, const StrBlob& rhs) { - return *lhs.data == *rhs.data; + return *lhs.data == *rhs.data; } -bool operator!=(const StrBlob &lhs, const StrBlob &rhs) +bool operator!=(const StrBlob& lhs, const StrBlob& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator< (const StrBlob &lhs, const StrBlob &rhs) +bool operator<(const StrBlob& lhs, const StrBlob& rhs) { - return std::lexicographical_compare(lhs.data->begin(), lhs.data->end(), rhs.data->begin(), rhs.data->end()); + return std::lexicographical_compare(lhs.data->begin(), lhs.data->end(), + rhs.data->begin(), rhs.data->end()); } -bool operator> (const StrBlob &lhs, const StrBlob &rhs) +bool operator>(const StrBlob& lhs, const StrBlob& rhs) { - return rhs < lhs; + return rhs < lhs; } -bool operator<=(const StrBlob &lhs, const StrBlob &rhs) +bool operator<=(const StrBlob& lhs, const StrBlob& rhs) { - return !(rhs < lhs); + return !(rhs < lhs); } -bool operator>=(const StrBlob &lhs, const StrBlob &rhs) +bool operator>=(const StrBlob& lhs, const StrBlob& rhs) { - return !(lhs < rhs); + return !(lhs < rhs); } //================================================================ @@ -43,34 +44,34 @@ bool operator>=(const StrBlob &lhs, const StrBlob &rhs) // //================================================================ -bool operator==(const StrBlobPtr &lhs, const StrBlobPtr &rhs) +bool operator==(const StrBlobPtr& lhs, const StrBlobPtr& rhs) { - return lhs.curr == rhs.curr; + return lhs.curr == rhs.curr; } -bool operator!=(const StrBlobPtr &lhs, const StrBlobPtr &rhs) +bool operator!=(const StrBlobPtr& lhs, const StrBlobPtr& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator< (const StrBlobPtr &x, const StrBlobPtr &y) +bool operator<(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr < y.curr; + return x.curr < y.curr; } -bool operator> (const StrBlobPtr &x, const StrBlobPtr &y) +bool operator>(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr > y.curr; + return x.curr > y.curr; } -bool operator<=(const StrBlobPtr &x, const StrBlobPtr &y) +bool operator<=(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr <= y.curr; + return x.curr <= y.curr; } -bool operator>=(const StrBlobPtr &x, const StrBlobPtr &y) +bool operator>=(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr >= y.curr; + return x.curr >= y.curr; } //================================================================ @@ -79,34 +80,34 @@ bool operator>=(const StrBlobPtr &x, const StrBlobPtr &y) // //================================================================ -bool operator==(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator==(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr == rhs.curr; + return lhs.curr == rhs.curr; } -bool operator!=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator!=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator< (const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator<(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr < rhs.curr; + return lhs.curr < rhs.curr; } -bool operator> (const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator>(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr > rhs.curr; + return lhs.curr > rhs.curr; } -bool operator<=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator<=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr <= rhs.curr; + return lhs.curr <= rhs.curr; } -bool operator>=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator>=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr >= rhs.curr; + return lhs.curr >= rhs.curr; } //================================================================== @@ -115,20 +116,20 @@ bool operator>=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) // //================================================================== -StrBlob& StrBlob::operator=(const StrBlob &lhs) +StrBlob& StrBlob::operator=(const StrBlob& lhs) { - data = make_shared>(*lhs.data); - return *this; + data = make_shared>(*lhs.data); + return *this; } -StrBlob& StrBlob::operator=(StrBlob &&rhs) NOEXCEPT +StrBlob& StrBlob::operator=(StrBlob&& rhs) NOEXCEPT { - if (this != &rhs) { - data = std::move(rhs.data); - rhs.data = nullptr; - } + if (this != &rhs) { + data = std::move(rhs.data); + rhs.data = nullptr; + } - return *this; + return *this; } //================================================================== @@ -139,12 +140,12 @@ StrBlob& StrBlob::operator=(StrBlob &&rhs) NOEXCEPT StrBlobPtr StrBlob::begin() { - return StrBlobPtr(*this); + return StrBlobPtr(*this); } StrBlobPtr StrBlob::end() { - return StrBlobPtr(*this, data->size()); + return StrBlobPtr(*this, data->size()); } ConstStrBlobPtr StrBlob::cbegin() const diff --git a/ch14/ex14_27_28_StrBlob.h b/ch14/ex14_27_28_StrBlob.h index 7349031c..1c93a20f 100644 --- a/ch14/ex14_27_28_StrBlob.h +++ b/ch14/ex14_27_28_StrBlob.h @@ -24,7 +24,8 @@ using std::string; using std::initializer_list; #include -using std::make_shared; using std::shared_ptr; +using std::make_shared; +using std::shared_ptr; #include @@ -44,28 +45,30 @@ class ConstStrBlobPtr; //================================================================================= class StrBlob { - using size_type = vector::size_type; - friend class ConstStrBlobPtr; - friend class StrBlobPtr; - friend bool operator==(const StrBlob&, const StrBlob&); - friend bool operator!=(const StrBlob&, const StrBlob&); - friend bool operator< (const StrBlob&, const StrBlob&); - friend bool operator> (const StrBlob&, const StrBlob&); - friend bool operator<=(const StrBlob&, const StrBlob&); - friend bool operator>=(const StrBlob&, const StrBlob&); + using size_type = vector::size_type; + friend class ConstStrBlobPtr; + friend class StrBlobPtr; + friend bool operator==(const StrBlob&, const StrBlob&); + friend bool operator!=(const StrBlob&, const StrBlob&); + friend bool operator<(const StrBlob&, const StrBlob&); + friend bool operator>(const StrBlob&, const StrBlob&); + friend bool operator<=(const StrBlob&, const StrBlob&); + friend bool operator>=(const StrBlob&, const StrBlob&); public: - StrBlob() : data(make_shared>()) {} - StrBlob(initializer_list il) : data(make_shared>(il)) {} + StrBlob() : data(make_shared>()) {} + StrBlob(initializer_list il) : data(make_shared>(il)) + { + } - StrBlob(const StrBlob &sb) : data(make_shared>(*sb.data)) {} - StrBlob& operator=(const StrBlob&); + StrBlob(const StrBlob& sb) : data(make_shared>(*sb.data)) {} + StrBlob& operator=(const StrBlob&); - StrBlob(StrBlob &&rhs) NOEXCEPT : data(std::move(rhs.data)) {} - StrBlob& operator=(StrBlob &&) NOEXCEPT; + StrBlob(StrBlob&& rhs) NOEXCEPT : data(std::move(rhs.data)) {} + StrBlob& operator=(StrBlob&&) NOEXCEPT; - StrBlobPtr begin(); - StrBlobPtr end(); + StrBlobPtr begin(); + StrBlobPtr end(); ConstStrBlobPtr cbegin() const; ConstStrBlobPtr cend() const; @@ -76,61 +79,61 @@ class StrBlob { size_type size() const { return data->size(); } bool empty() const { return data->empty(); } - void push_back(const string &t) { data->push_back(t); } - void push_back(string &&s) { data->push_back(std::move(s)); } + void push_back(const string& t) { data->push_back(t); } + void push_back(string&& s) { data->push_back(std::move(s)); } - void pop_back(); - string& front(); - string& back(); - const string& front() const; - const string& back() const; + void pop_back(); + string& front(); + string& back(); + const string& front() const; + const string& back() const; private: - void check(size_type, const string&) const; + void check(size_type, const string&) const; shared_ptr> data; }; bool operator==(const StrBlob&, const StrBlob&); bool operator!=(const StrBlob&, const StrBlob&); -bool operator< (const StrBlob&, const StrBlob&); -bool operator> (const StrBlob&, const StrBlob&); +bool operator<(const StrBlob&, const StrBlob&); +bool operator>(const StrBlob&, const StrBlob&); bool operator<=(const StrBlob&, const StrBlob&); bool operator>=(const StrBlob&, const StrBlob&); inline void StrBlob::pop_back() { - check(0, "pop_back on empty StrBlob"); - data->pop_back(); + check(0, "pop_back on empty StrBlob"); + data->pop_back(); } inline string& StrBlob::front() { - check(0, "front on empty StrBlob"); - return data->front(); + check(0, "front on empty StrBlob"); + return data->front(); } inline string& StrBlob::back() { - check(0, "back on empty StrBlob"); - return data->back(); + check(0, "back on empty StrBlob"); + return data->back(); } inline const string& StrBlob::front() const { - check(0, "front on empty StrBlob"); - return data->front(); + check(0, "front on empty StrBlob"); + return data->front(); } inline const string& StrBlob::back() const { - check(0, "back on empty StrBlob"); - return data->back(); + check(0, "back on empty StrBlob"); + return data->back(); } -inline void StrBlob::check(size_type i, const string &msg) const +inline void StrBlob::check(size_type i, const string& msg) const { - if (i >= data->size()) throw std::out_of_range(msg); + if (i >= data->size()) throw std::out_of_range(msg); } inline string& StrBlob::operator[](size_t n) @@ -152,112 +155,113 @@ inline const string& StrBlob::operator[](size_t n) const //================================================================================= class StrBlobPtr { - friend bool operator==(const StrBlobPtr&, const StrBlobPtr&); - friend bool operator!=(const StrBlobPtr&, const StrBlobPtr&); - friend bool operator< (const StrBlobPtr&, const StrBlobPtr&); - friend bool operator> (const StrBlobPtr&, const StrBlobPtr&); - friend bool operator<=(const StrBlobPtr&, const StrBlobPtr&); - friend bool operator>=(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator==(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator!=(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator<(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator>(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator<=(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator>=(const StrBlobPtr&, const StrBlobPtr&); public: - StrBlobPtr() : curr(0) {} - StrBlobPtr(StrBlob &s, size_t sz = 0) : wptr(s.data), curr(sz) {} - - string& deref() const; - StrBlobPtr& operator++(); - StrBlobPtr& operator--(); - StrBlobPtr operator++(int); - StrBlobPtr operator--(int); - StrBlobPtr& operator+=(size_t); - StrBlobPtr& operator-=(size_t); - StrBlobPtr operator+(size_t) const; - StrBlobPtr operator-(size_t) const; + StrBlobPtr() : curr(0) {} + StrBlobPtr(StrBlob& s, size_t sz = 0) : wptr(s.data), curr(sz) {} + + string& deref() const; + StrBlobPtr& operator++(); + StrBlobPtr& operator--(); + StrBlobPtr operator++(int); + StrBlobPtr operator--(int); + StrBlobPtr& operator+=(size_t); + StrBlobPtr& operator-=(size_t); + StrBlobPtr operator+(size_t) const; + StrBlobPtr operator-(size_t) const; string& operator[](size_t n); const string& operator[](size_t n) const; private: - shared_ptr> check(size_t, const string&) const; + shared_ptr> check(size_t, const string&) const; - std::weak_ptr> wptr; - size_t curr; + std::weak_ptr> wptr; + size_t curr; }; bool operator==(const StrBlobPtr&, const StrBlobPtr&); bool operator!=(const StrBlobPtr&, const StrBlobPtr&); -bool operator< (const StrBlobPtr&, const StrBlobPtr&); -bool operator> (const StrBlobPtr&, const StrBlobPtr&); +bool operator<(const StrBlobPtr&, const StrBlobPtr&); +bool operator>(const StrBlobPtr&, const StrBlobPtr&); bool operator<=(const StrBlobPtr&, const StrBlobPtr&); bool operator>=(const StrBlobPtr&, const StrBlobPtr&); inline string& StrBlobPtr::deref() const { - auto p = check(curr, "dereference past end"); - return (*p)[curr]; + auto p = check(curr, "dereference past end"); + return (*p)[curr]; } inline StrBlobPtr& StrBlobPtr::operator++() { - check(curr, "increment past end of StrBlobPtr"); - ++curr; - return *this; + check(curr, "increment past end of StrBlobPtr"); + ++curr; + return *this; } inline StrBlobPtr& StrBlobPtr::operator--() { - --curr; - check(-1, "decrement past begin of StrBlobPtr"); - return *this; + --curr; + check(-1, "decrement past begin of StrBlobPtr"); + return *this; } inline StrBlobPtr StrBlobPtr::operator++(int) { - StrBlobPtr ret = *this; - ++*this; - return ret; + StrBlobPtr ret = *this; + ++*this; + return ret; } inline StrBlobPtr StrBlobPtr::operator--(int) { - StrBlobPtr ret = *this; - --*this; - return ret; + StrBlobPtr ret = *this; + --*this; + return ret; } inline StrBlobPtr& StrBlobPtr::operator+=(size_t n) { - curr += n; - check(curr, "increment past end of StrBlobPtr"); - return *this; + curr += n; + check(curr, "increment past end of StrBlobPtr"); + return *this; } inline StrBlobPtr& StrBlobPtr::operator-=(size_t n) { - curr -= n; - check(curr, "increment past end of StrBlobPtr"); - return *this; + curr -= n; + check(curr, "increment past end of StrBlobPtr"); + return *this; } inline StrBlobPtr StrBlobPtr::operator+(size_t n) const { - StrBlobPtr ret = *this; - ret += n; - return ret; + StrBlobPtr ret = *this; + ret += n; + return ret; } inline StrBlobPtr StrBlobPtr::operator-(size_t n) const { - StrBlobPtr ret = *this; - ret -= n; - return ret; + StrBlobPtr ret = *this; + ret -= n; + return ret; } -inline shared_ptr> StrBlobPtr::check(size_t i, const string &msg) const +inline shared_ptr> StrBlobPtr::check(size_t i, + const string& msg) const { - auto ret = wptr.lock(); - if (!ret) throw std::runtime_error("unbound StrBlobPtr"); - if (i >= ret->size()) throw std::out_of_range(msg); - return ret; + auto ret = wptr.lock(); + if (!ret) throw std::runtime_error("unbound StrBlobPtr"); + if (i >= ret->size()) throw std::out_of_range(msg); + return ret; } inline string& StrBlobPtr::operator[](size_t n) @@ -279,31 +283,31 @@ inline const string& StrBlobPtr::operator[](size_t n) const //================================================================================= class ConstStrBlobPtr { - friend bool operator==(const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator!=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator< (const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator> (const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator<=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator>=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator==(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator!=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator<(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator>(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator<=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator>=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); public: - ConstStrBlobPtr() : curr(0) {} - ConstStrBlobPtr(const StrBlob &s, size_t sz = 0) : wptr(s.data), curr(sz) {} - - const string& deref() const; - ConstStrBlobPtr& operator++(); - ConstStrBlobPtr& operator--(); - ConstStrBlobPtr operator++(int); - ConstStrBlobPtr operator--(int); - ConstStrBlobPtr& operator+=(size_t); - ConstStrBlobPtr& operator-=(size_t); - ConstStrBlobPtr operator+(size_t) const; - ConstStrBlobPtr operator-(size_t) const; + ConstStrBlobPtr() : curr(0) {} + ConstStrBlobPtr(const StrBlob& s, size_t sz = 0) : wptr(s.data), curr(sz) {} + + const string& deref() const; + ConstStrBlobPtr& operator++(); + ConstStrBlobPtr& operator--(); + ConstStrBlobPtr operator++(int); + ConstStrBlobPtr operator--(int); + ConstStrBlobPtr& operator+=(size_t); + ConstStrBlobPtr& operator-=(size_t); + ConstStrBlobPtr operator+(size_t) const; + ConstStrBlobPtr operator-(size_t) const; const string& operator[](size_t n) const; private: - std::shared_ptr> check(size_t, const string&) const; + std::shared_ptr> check(size_t, const string&) const; std::weak_ptr> wptr; size_t curr; @@ -311,79 +315,80 @@ class ConstStrBlobPtr { bool operator==(const ConstStrBlobPtr&, const ConstStrBlobPtr&); bool operator!=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); -bool operator< (const ConstStrBlobPtr&, const ConstStrBlobPtr&); -bool operator> (const ConstStrBlobPtr&, const ConstStrBlobPtr&); +bool operator<(const ConstStrBlobPtr&, const ConstStrBlobPtr&); +bool operator>(const ConstStrBlobPtr&, const ConstStrBlobPtr&); bool operator<=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); bool operator>=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); inline const string& ConstStrBlobPtr::deref() const { - auto p = check(curr, "dereference past end"); - return (*p)[curr]; + auto p = check(curr, "dereference past end"); + return (*p)[curr]; } inline ConstStrBlobPtr& ConstStrBlobPtr::operator++() { - check(curr, "increment past end of ConstStrBlobPtr"); - ++curr; - return *this; + check(curr, "increment past end of ConstStrBlobPtr"); + ++curr; + return *this; } inline ConstStrBlobPtr& ConstStrBlobPtr::operator--() { - --curr; - check(-1, "decrement past begin of ConstStrBlobPtr"); - return *this; + --curr; + check(-1, "decrement past begin of ConstStrBlobPtr"); + return *this; } inline ConstStrBlobPtr ConstStrBlobPtr::operator++(int) { - ConstStrBlobPtr ret = *this; - ++*this; - return ret; + ConstStrBlobPtr ret = *this; + ++*this; + return ret; } inline ConstStrBlobPtr ConstStrBlobPtr::operator--(int) { - ConstStrBlobPtr ret = *this; - --*this; - return ret; + ConstStrBlobPtr ret = *this; + --*this; + return ret; } inline ConstStrBlobPtr& ConstStrBlobPtr::operator+=(size_t n) { - curr += n; - check(curr, "increment past end of ConstStrBlobPtr"); - return *this; + curr += n; + check(curr, "increment past end of ConstStrBlobPtr"); + return *this; } inline ConstStrBlobPtr& ConstStrBlobPtr::operator-=(size_t n) { - curr -= n; - check(curr, "increment past end of ConstStrBlobPtr"); - return *this; + curr -= n; + check(curr, "increment past end of ConstStrBlobPtr"); + return *this; } inline ConstStrBlobPtr ConstStrBlobPtr::operator+(size_t n) const { - ConstStrBlobPtr ret = *this; - ret += n; - return ret; + ConstStrBlobPtr ret = *this; + ret += n; + return ret; } inline ConstStrBlobPtr ConstStrBlobPtr::operator-(size_t n) const { - ConstStrBlobPtr ret = *this; - ret -= n; - return ret; + ConstStrBlobPtr ret = *this; + ret -= n; + return ret; } -inline std::shared_ptr> ConstStrBlobPtr::check(size_t i, const string &msg) const +inline std::shared_ptr> +ConstStrBlobPtr::check(size_t i, const string& msg) const { - auto ret = wptr.lock(); - if (!ret) throw std::runtime_error("unbound StrBlobPtr"); - if (i >= ret->size()) throw std::out_of_range(msg); - return ret; + auto ret = wptr.lock(); + if (!ret) throw std::runtime_error("unbound StrBlobPtr"); + if (i >= ret->size()) throw std::out_of_range(msg); + return ret; } inline const string& ConstStrBlobPtr::operator[](size_t n) const @@ -392,4 +397,4 @@ inline const string& ConstStrBlobPtr::operator[](size_t n) const return (*p)[n]; } -#endif //CP5_STRBLOB_H_ +#endif // CP5_STRBLOB_H_ diff --git a/ch14/ex14_27_28_StrBlobTest.cpp b/ch14/ex14_27_28_StrBlobTest.cpp index 8dbf45e1..809cce53 100644 --- a/ch14/ex14_27_28_StrBlobTest.cpp +++ b/ch14/ex14_27_28_StrBlobTest.cpp @@ -3,16 +3,16 @@ int main() { - StrBlob sb1{ "a", "b", "c" }; + StrBlob sb1{"a", "b", "c"}; StrBlob sb2 = sb1; sb2[2] = "b"; - if (sb1 > sb2) { - for (StrBlobPtr iter = sb1.begin(); iter < sb1.end(); ++iter) - std::cout << iter.deref() << " "; - std::cout << std::endl; - } + if (sb1 > sb2) { + for (StrBlobPtr iter = sb1.begin(); iter < sb1.end(); ++iter) + std::cout << iter.deref() << " "; + std::cout << std::endl; + } ConstStrBlobPtr iter(sb2); std::cout << (iter + 2).deref() << std::endl; diff --git a/ch14/ex14_30_StrBlob.cpp b/ch14/ex14_30_StrBlob.cpp index e24f4eba..73533a72 100644 --- a/ch14/ex14_30_StrBlob.cpp +++ b/ch14/ex14_30_StrBlob.cpp @@ -7,34 +7,35 @@ // //================================================================== -bool operator==(const StrBlob &lhs, const StrBlob &rhs) +bool operator==(const StrBlob& lhs, const StrBlob& rhs) { - return *lhs.data == *rhs.data; + return *lhs.data == *rhs.data; } -bool operator!=(const StrBlob &lhs, const StrBlob &rhs) +bool operator!=(const StrBlob& lhs, const StrBlob& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator< (const StrBlob &lhs, const StrBlob &rhs) +bool operator<(const StrBlob& lhs, const StrBlob& rhs) { - return std::lexicographical_compare(lhs.data->begin(), lhs.data->end(), rhs.data->begin(), rhs.data->end()); + return std::lexicographical_compare(lhs.data->begin(), lhs.data->end(), + rhs.data->begin(), rhs.data->end()); } -bool operator> (const StrBlob &lhs, const StrBlob &rhs) +bool operator>(const StrBlob& lhs, const StrBlob& rhs) { - return rhs < lhs; + return rhs < lhs; } -bool operator<=(const StrBlob &lhs, const StrBlob &rhs) +bool operator<=(const StrBlob& lhs, const StrBlob& rhs) { - return !(rhs < lhs); + return !(rhs < lhs); } -bool operator>=(const StrBlob &lhs, const StrBlob &rhs) +bool operator>=(const StrBlob& lhs, const StrBlob& rhs) { - return !(lhs < rhs); + return !(lhs < rhs); } //================================================================ @@ -43,34 +44,34 @@ bool operator>=(const StrBlob &lhs, const StrBlob &rhs) // //================================================================ -bool operator==(const StrBlobPtr &lhs, const StrBlobPtr &rhs) +bool operator==(const StrBlobPtr& lhs, const StrBlobPtr& rhs) { - return lhs.curr == rhs.curr; + return lhs.curr == rhs.curr; } -bool operator!=(const StrBlobPtr &lhs, const StrBlobPtr &rhs) +bool operator!=(const StrBlobPtr& lhs, const StrBlobPtr& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator< (const StrBlobPtr &x, const StrBlobPtr &y) +bool operator<(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr < y.curr; + return x.curr < y.curr; } -bool operator> (const StrBlobPtr &x, const StrBlobPtr &y) +bool operator>(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr > y.curr; + return x.curr > y.curr; } -bool operator<=(const StrBlobPtr &x, const StrBlobPtr &y) +bool operator<=(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr <= y.curr; + return x.curr <= y.curr; } -bool operator>=(const StrBlobPtr &x, const StrBlobPtr &y) +bool operator>=(const StrBlobPtr& x, const StrBlobPtr& y) { - return x.curr >= y.curr; + return x.curr >= y.curr; } //================================================================ @@ -79,34 +80,34 @@ bool operator>=(const StrBlobPtr &x, const StrBlobPtr &y) // //================================================================ -bool operator==(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator==(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr == rhs.curr; + return lhs.curr == rhs.curr; } -bool operator!=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator!=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } -bool operator< (const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator<(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr < rhs.curr; + return lhs.curr < rhs.curr; } -bool operator> (const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator>(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr > rhs.curr; + return lhs.curr > rhs.curr; } -bool operator<=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator<=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr <= rhs.curr; + return lhs.curr <= rhs.curr; } -bool operator>=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) +bool operator>=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { - return lhs.curr >= rhs.curr; + return lhs.curr >= rhs.curr; } //================================================================== @@ -115,20 +116,20 @@ bool operator>=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs) // //================================================================== -StrBlob& StrBlob::operator=(const StrBlob &lhs) +StrBlob& StrBlob::operator=(const StrBlob& lhs) { - data = make_shared>(*lhs.data); - return *this; + data = make_shared>(*lhs.data); + return *this; } -StrBlob& StrBlob::operator=(StrBlob &&rhs) NOEXCEPT +StrBlob& StrBlob::operator=(StrBlob&& rhs) NOEXCEPT { - if (this != &rhs) { - data = std::move(rhs.data); - rhs.data = nullptr; - } + if (this != &rhs) { + data = std::move(rhs.data); + rhs.data = nullptr; + } - return *this; + return *this; } //================================================================== @@ -139,12 +140,12 @@ StrBlob& StrBlob::operator=(StrBlob &&rhs) NOEXCEPT StrBlobPtr StrBlob::begin() { - return StrBlobPtr(*this); + return StrBlobPtr(*this); } StrBlobPtr StrBlob::end() { - return StrBlobPtr(*this, data->size()); + return StrBlobPtr(*this, data->size()); } ConstStrBlobPtr StrBlob::cbegin() const diff --git a/ch14/ex14_30_StrBlob.h b/ch14/ex14_30_StrBlob.h index 90b9eb83..3a76d9ce 100644 --- a/ch14/ex14_30_StrBlob.h +++ b/ch14/ex14_30_StrBlob.h @@ -24,7 +24,8 @@ using std::string; using std::initializer_list; #include -using std::make_shared; using std::shared_ptr; +using std::make_shared; +using std::shared_ptr; #include @@ -44,28 +45,30 @@ class ConstStrBlobPtr; //================================================================================= class StrBlob { - using size_type = vector::size_type; - friend class ConstStrBlobPtr; - friend class StrBlobPtr; - friend bool operator==(const StrBlob&, const StrBlob&); - friend bool operator!=(const StrBlob&, const StrBlob&); - friend bool operator< (const StrBlob&, const StrBlob&); - friend bool operator> (const StrBlob&, const StrBlob&); - friend bool operator<=(const StrBlob&, const StrBlob&); - friend bool operator>=(const StrBlob&, const StrBlob&); + using size_type = vector::size_type; + friend class ConstStrBlobPtr; + friend class StrBlobPtr; + friend bool operator==(const StrBlob&, const StrBlob&); + friend bool operator!=(const StrBlob&, const StrBlob&); + friend bool operator<(const StrBlob&, const StrBlob&); + friend bool operator>(const StrBlob&, const StrBlob&); + friend bool operator<=(const StrBlob&, const StrBlob&); + friend bool operator>=(const StrBlob&, const StrBlob&); public: - StrBlob() : data(make_shared>()) {} - StrBlob(initializer_list il) : data(make_shared>(il)) {} + StrBlob() : data(make_shared>()) {} + StrBlob(initializer_list il) : data(make_shared>(il)) + { + } - StrBlob(const StrBlob &sb) : data(make_shared>(*sb.data)) {} - StrBlob& operator=(const StrBlob&); + StrBlob(const StrBlob& sb) : data(make_shared>(*sb.data)) {} + StrBlob& operator=(const StrBlob&); - StrBlob(StrBlob &&rhs) NOEXCEPT : data(std::move(rhs.data)) {} - StrBlob& operator=(StrBlob &&) NOEXCEPT; + StrBlob(StrBlob&& rhs) NOEXCEPT : data(std::move(rhs.data)) {} + StrBlob& operator=(StrBlob&&) NOEXCEPT; - StrBlobPtr begin(); - StrBlobPtr end(); + StrBlobPtr begin(); + StrBlobPtr end(); ConstStrBlobPtr cbegin() const; ConstStrBlobPtr cend() const; @@ -76,61 +79,61 @@ class StrBlob { size_type size() const { return data->size(); } bool empty() const { return data->empty(); } - void push_back(const string &t) { data->push_back(t); } - void push_back(string &&s) { data->push_back(std::move(s)); } + void push_back(const string& t) { data->push_back(t); } + void push_back(string&& s) { data->push_back(std::move(s)); } - void pop_back(); - string& front(); - string& back(); - const string& front() const; - const string& back() const; + void pop_back(); + string& front(); + string& back(); + const string& front() const; + const string& back() const; private: - void check(size_type, const string&) const; + void check(size_type, const string&) const; shared_ptr> data; }; bool operator==(const StrBlob&, const StrBlob&); bool operator!=(const StrBlob&, const StrBlob&); -bool operator< (const StrBlob&, const StrBlob&); -bool operator> (const StrBlob&, const StrBlob&); +bool operator<(const StrBlob&, const StrBlob&); +bool operator>(const StrBlob&, const StrBlob&); bool operator<=(const StrBlob&, const StrBlob&); bool operator>=(const StrBlob&, const StrBlob&); inline void StrBlob::pop_back() { - check(0, "pop_back on empty StrBlob"); - data->pop_back(); + check(0, "pop_back on empty StrBlob"); + data->pop_back(); } inline string& StrBlob::front() { - check(0, "front on empty StrBlob"); - return data->front(); + check(0, "front on empty StrBlob"); + return data->front(); } inline string& StrBlob::back() { - check(0, "back on empty StrBlob"); - return data->back(); + check(0, "back on empty StrBlob"); + return data->back(); } inline const string& StrBlob::front() const { - check(0, "front on empty StrBlob"); - return data->front(); + check(0, "front on empty StrBlob"); + return data->front(); } inline const string& StrBlob::back() const { - check(0, "back on empty StrBlob"); - return data->back(); + check(0, "back on empty StrBlob"); + return data->back(); } -inline void StrBlob::check(size_type i, const string &msg) const +inline void StrBlob::check(size_type i, const string& msg) const { - if (i >= data->size()) throw std::out_of_range(msg); + if (i >= data->size()) throw std::out_of_range(msg); } inline string& StrBlob::operator[](size_t n) @@ -152,112 +155,113 @@ inline const string& StrBlob::operator[](size_t n) const //================================================================================= class StrBlobPtr { - friend bool operator==(const StrBlobPtr&, const StrBlobPtr&); - friend bool operator!=(const StrBlobPtr&, const StrBlobPtr&); - friend bool operator< (const StrBlobPtr&, const StrBlobPtr&); - friend bool operator> (const StrBlobPtr&, const StrBlobPtr&); - friend bool operator<=(const StrBlobPtr&, const StrBlobPtr&); - friend bool operator>=(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator==(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator!=(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator<(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator>(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator<=(const StrBlobPtr&, const StrBlobPtr&); + friend bool operator>=(const StrBlobPtr&, const StrBlobPtr&); public: - StrBlobPtr() : curr(0) {} - StrBlobPtr(StrBlob &s, size_t sz = 0) : wptr(s.data), curr(sz) {} - - string& deref() const; - StrBlobPtr& operator++(); - StrBlobPtr& operator--(); - StrBlobPtr operator++(int); - StrBlobPtr operator--(int); - StrBlobPtr& operator+=(size_t); - StrBlobPtr& operator-=(size_t); - StrBlobPtr operator+(size_t) const; - StrBlobPtr operator-(size_t) const; + StrBlobPtr() : curr(0) {} + StrBlobPtr(StrBlob& s, size_t sz = 0) : wptr(s.data), curr(sz) {} + + string& deref() const; + StrBlobPtr& operator++(); + StrBlobPtr& operator--(); + StrBlobPtr operator++(int); + StrBlobPtr operator--(int); + StrBlobPtr& operator+=(size_t); + StrBlobPtr& operator-=(size_t); + StrBlobPtr operator+(size_t) const; + StrBlobPtr operator-(size_t) const; string& operator[](size_t n); const string& operator[](size_t n) const; private: - shared_ptr> check(size_t, const string&) const; + shared_ptr> check(size_t, const string&) const; - std::weak_ptr> wptr; - size_t curr; + std::weak_ptr> wptr; + size_t curr; }; bool operator==(const StrBlobPtr&, const StrBlobPtr&); bool operator!=(const StrBlobPtr&, const StrBlobPtr&); -bool operator< (const StrBlobPtr&, const StrBlobPtr&); -bool operator> (const StrBlobPtr&, const StrBlobPtr&); +bool operator<(const StrBlobPtr&, const StrBlobPtr&); +bool operator>(const StrBlobPtr&, const StrBlobPtr&); bool operator<=(const StrBlobPtr&, const StrBlobPtr&); bool operator>=(const StrBlobPtr&, const StrBlobPtr&); inline string& StrBlobPtr::deref() const { - auto p = check(curr, "dereference past end"); - return (*p)[curr]; + auto p = check(curr, "dereference past end"); + return (*p)[curr]; } inline StrBlobPtr& StrBlobPtr::operator++() { - check(curr, "increment past end of StrBlobPtr"); - ++curr; - return *this; + check(curr, "increment past end of StrBlobPtr"); + ++curr; + return *this; } inline StrBlobPtr& StrBlobPtr::operator--() { - --curr; - check(-1, "decrement past begin of StrBlobPtr"); - return *this; + --curr; + check(-1, "decrement past begin of StrBlobPtr"); + return *this; } inline StrBlobPtr StrBlobPtr::operator++(int) { - StrBlobPtr ret = *this; - ++*this; - return ret; + StrBlobPtr ret = *this; + ++*this; + return ret; } inline StrBlobPtr StrBlobPtr::operator--(int) { - StrBlobPtr ret = *this; - --*this; - return ret; + StrBlobPtr ret = *this; + --*this; + return ret; } inline StrBlobPtr& StrBlobPtr::operator+=(size_t n) { - curr += n; - check(curr, "increment past end of StrBlobPtr"); - return *this; + curr += n; + check(curr, "increment past end of StrBlobPtr"); + return *this; } inline StrBlobPtr& StrBlobPtr::operator-=(size_t n) { - curr -= n; - check(curr, "increment past end of StrBlobPtr"); - return *this; + curr -= n; + check(curr, "increment past end of StrBlobPtr"); + return *this; } inline StrBlobPtr StrBlobPtr::operator+(size_t n) const { - StrBlobPtr ret = *this; - ret += n; - return ret; + StrBlobPtr ret = *this; + ret += n; + return ret; } inline StrBlobPtr StrBlobPtr::operator-(size_t n) const { - StrBlobPtr ret = *this; - ret -= n; - return ret; + StrBlobPtr ret = *this; + ret -= n; + return ret; } -inline shared_ptr> StrBlobPtr::check(size_t i, const string &msg) const +inline shared_ptr> StrBlobPtr::check(size_t i, + const string& msg) const { - auto ret = wptr.lock(); - if (!ret) throw std::runtime_error("unbound StrBlobPtr"); - if (i >= ret->size()) throw std::out_of_range(msg); - return ret; + auto ret = wptr.lock(); + if (!ret) throw std::runtime_error("unbound StrBlobPtr"); + if (i >= ret->size()) throw std::out_of_range(msg); + return ret; } inline string& StrBlobPtr::operator[](size_t n) @@ -279,32 +283,32 @@ inline const string& StrBlobPtr::operator[](size_t n) const //================================================================================= class ConstStrBlobPtr { - friend bool operator==(const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator!=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator< (const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator> (const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator<=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); - friend bool operator>=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator==(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator!=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator<(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator>(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator<=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); + friend bool operator>=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); public: - ConstStrBlobPtr() : curr(0) {} - ConstStrBlobPtr(const StrBlob &s, size_t sz = 0) : wptr(s.data), curr(sz) {} - - const string& operator*() const; - const string* operator->() const; - ConstStrBlobPtr& operator++(); - ConstStrBlobPtr& operator--(); - ConstStrBlobPtr operator++(int); - ConstStrBlobPtr operator--(int); - ConstStrBlobPtr& operator+=(size_t); - ConstStrBlobPtr& operator-=(size_t); - ConstStrBlobPtr operator+(size_t) const; - ConstStrBlobPtr operator-(size_t) const; + ConstStrBlobPtr() : curr(0) {} + ConstStrBlobPtr(const StrBlob& s, size_t sz = 0) : wptr(s.data), curr(sz) {} + + const string& operator*() const; + const string* operator->() const; + ConstStrBlobPtr& operator++(); + ConstStrBlobPtr& operator--(); + ConstStrBlobPtr operator++(int); + ConstStrBlobPtr operator--(int); + ConstStrBlobPtr& operator+=(size_t); + ConstStrBlobPtr& operator-=(size_t); + ConstStrBlobPtr operator+(size_t) const; + ConstStrBlobPtr operator-(size_t) const; const string& operator[](size_t n) const; private: - std::shared_ptr> check(size_t, const string&) const; + std::shared_ptr> check(size_t, const string&) const; std::weak_ptr> wptr; size_t curr; @@ -312,84 +316,85 @@ class ConstStrBlobPtr { bool operator==(const ConstStrBlobPtr&, const ConstStrBlobPtr&); bool operator!=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); -bool operator< (const ConstStrBlobPtr&, const ConstStrBlobPtr&); -bool operator> (const ConstStrBlobPtr&, const ConstStrBlobPtr&); +bool operator<(const ConstStrBlobPtr&, const ConstStrBlobPtr&); +bool operator>(const ConstStrBlobPtr&, const ConstStrBlobPtr&); bool operator<=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); bool operator>=(const ConstStrBlobPtr&, const ConstStrBlobPtr&); inline const string& ConstStrBlobPtr::operator*() const { - auto p = check(curr, "dereference past end"); - return (*p)[curr]; + auto p = check(curr, "dereference past end"); + return (*p)[curr]; } inline const string* ConstStrBlobPtr::operator->() const { - return & this->operator*(); + return &this->operator*(); } inline ConstStrBlobPtr& ConstStrBlobPtr::operator++() { - check(curr, "increment past end of ConstStrBlobPtr"); - ++curr; - return *this; + check(curr, "increment past end of ConstStrBlobPtr"); + ++curr; + return *this; } inline ConstStrBlobPtr& ConstStrBlobPtr::operator--() { - --curr; - check(-1, "decrement past begin of ConstStrBlobPtr"); - return *this; + --curr; + check(-1, "decrement past begin of ConstStrBlobPtr"); + return *this; } inline ConstStrBlobPtr ConstStrBlobPtr::operator++(int) { - ConstStrBlobPtr ret = *this; - ++*this; - return ret; + ConstStrBlobPtr ret = *this; + ++*this; + return ret; } inline ConstStrBlobPtr ConstStrBlobPtr::operator--(int) { - ConstStrBlobPtr ret = *this; - --*this; - return ret; + ConstStrBlobPtr ret = *this; + --*this; + return ret; } inline ConstStrBlobPtr& ConstStrBlobPtr::operator+=(size_t n) { - curr += n; - check(curr, "increment past end of ConstStrBlobPtr"); - return *this; + curr += n; + check(curr, "increment past end of ConstStrBlobPtr"); + return *this; } inline ConstStrBlobPtr& ConstStrBlobPtr::operator-=(size_t n) { - curr -= n; - check(curr, "increment past end of ConstStrBlobPtr"); - return *this; + curr -= n; + check(curr, "increment past end of ConstStrBlobPtr"); + return *this; } inline ConstStrBlobPtr ConstStrBlobPtr::operator+(size_t n) const { - ConstStrBlobPtr ret = *this; - ret += n; - return ret; + ConstStrBlobPtr ret = *this; + ret += n; + return ret; } inline ConstStrBlobPtr ConstStrBlobPtr::operator-(size_t n) const { - ConstStrBlobPtr ret = *this; - ret -= n; - return ret; + ConstStrBlobPtr ret = *this; + ret -= n; + return ret; } -inline std::shared_ptr> ConstStrBlobPtr::check(size_t i, const string &msg) const +inline std::shared_ptr> +ConstStrBlobPtr::check(size_t i, const string& msg) const { - auto ret = wptr.lock(); - if (!ret) throw std::runtime_error("unbound StrBlobPtr"); - if (i >= ret->size()) throw std::out_of_range(msg); - return ret; + auto ret = wptr.lock(); + if (!ret) throw std::runtime_error("unbound StrBlobPtr"); + if (i >= ret->size()) throw std::out_of_range(msg); + return ret; } inline const string& ConstStrBlobPtr::operator[](size_t n) const @@ -398,4 +403,4 @@ inline const string& ConstStrBlobPtr::operator[](size_t n) const return (*p)[n]; } -#endif //CP5_STRBLOB_H_ +#endif // CP5_STRBLOB_H_ diff --git a/ch14/ex14_30_StrBlobTest.cpp b/ch14/ex14_30_StrBlobTest.cpp index ef0cedb2..1ab54c49 100644 --- a/ch14/ex14_30_StrBlobTest.cpp +++ b/ch14/ex14_30_StrBlobTest.cpp @@ -3,16 +3,16 @@ int main() { - StrBlob sb1{ "a", "b", "c" }; + StrBlob sb1{"a", "b", "c"}; StrBlob sb2 = sb1; sb2[2] = "b"; - if (sb1 > sb2) { - for (ConstStrBlobPtr iter = sb1.cbegin(); iter != sb1.cend(); ++iter) - std::cout << *iter << " "; - std::cout << std::endl; - } + if (sb1 > sb2) { + for (ConstStrBlobPtr iter = sb1.cbegin(); iter != sb1.cend(); ++iter) + std::cout << *iter << " "; + std::cout << std::endl; + } ConstStrBlobPtr iter(sb2); std::cout << iter->size() << std::endl; diff --git a/ch14/ex14_32.cpp b/ch14/ex14_32.cpp index 32f2d4eb..a6770424 100644 --- a/ch14/ex14_32.cpp +++ b/ch14/ex14_32.cpp @@ -2,16 +2,14 @@ #include "ex14_30_StrBlob.h" #include -StrBlobPtr& -StrBlobPtr_pointer::operator *() +StrBlobPtr& StrBlobPtr_pointer::operator*() { return *(this->pointer); } -StrBlobPtr* -StrBlobPtr_pointer::operator ->() +StrBlobPtr* StrBlobPtr_pointer::operator->() { - return & this->operator *(); + return &this->operator*(); } int main() diff --git a/ch14/ex14_32.h b/ch14/ex14_32.h index eda3aaac..ca09d2f3 100644 --- a/ch14/ex14_32.h +++ b/ch14/ex14_32.h @@ -13,13 +13,12 @@ class StrBlobPtr; /** * @brief a class that holds a pointer to a StrBlobPtr. */ -class StrBlobPtr_pointer -{ +class StrBlobPtr_pointer { public: StrBlobPtr_pointer() = default; StrBlobPtr_pointer(StrBlobPtr* p) : pointer(p) {} - StrBlobPtr& operator *(); + StrBlobPtr& operator*(); StrBlobPtr* operator->(); private: diff --git a/ch14/ex14_35.cpp b/ch14/ex14_35.cpp index 0789f8c9..bc137978 100644 --- a/ch14/ex14_35.cpp +++ b/ch14/ex14_35.cpp @@ -3,15 +3,16 @@ class GetInput { public: - GetInput(std::istream &i = std::cin) : is(i) { } - std::string operator()() const { + GetInput(std::istream& i = std::cin) : is(i) {} + std::string operator()() const + { std::string str; std::getline(is, str); return is ? str : std::string(); } private: - std::istream &is; + std::istream& is; }; int main() diff --git a/ch14/ex14_36.cpp b/ch14/ex14_36.cpp index 2d4a4380..b4d47f3a 100644 --- a/ch14/ex14_36.cpp +++ b/ch14/ex14_36.cpp @@ -4,22 +4,23 @@ class GetInput { public: - GetInput(std::istream &i = std::cin) : is(i) { } - std::string operator()() const { + GetInput(std::istream& i = std::cin) : is(i) {} + std::string operator()() const + { std::string str; std::getline(is, str); return is ? str : std::string(); } private: - std::istream &is; + std::istream& is; }; int main() { GetInput getInput; std::vector vec; - for ( std::string tmp; !( tmp = getInput() ).empty(); ) vec.push_back( tmp ); - for (const auto &str : vec) std::cout << str << " "; + for (std::string tmp; !(tmp = getInput()).empty();) vec.push_back(tmp); + for (const auto& str : vec) std::cout << str << " "; std::cout << std::endl; } diff --git a/ch14/ex14_37.cpp b/ch14/ex14_37.cpp index a955ba88..bfcf6265 100644 --- a/ch14/ex14_37.cpp +++ b/ch14/ex14_37.cpp @@ -4,16 +4,15 @@ class IsEqual { int value; + public: IsEqual(int v) : value(v) {} - bool operator()(int elem) { - return elem == value; - } + bool operator()(int elem) { return elem == value; } }; int main() { - std::vector vec = {3,2,1,4,3,7,8,6}; + std::vector vec = {3, 2, 1, 4, 3, 7, 8, 6}; std::replace_if(vec.begin(), vec.end(), IsEqual(3), 5); for (int i : vec) std::cout << i << " "; std::cout << std::endl; diff --git a/ch14/ex14_38_39.cpp b/ch14/ex14_38_39.cpp index 1189e3a9..bc0d2041 100644 --- a/ch14/ex14_38_39.cpp +++ b/ch14/ex14_38_39.cpp @@ -22,11 +22,13 @@ #include #include -class BoundTest -{ +class BoundTest { public: - BoundTest(std::size_t l = 0, std::size_t u = 0) : lower(l), upper(u){} - bool operator() (const std::string& s) { return lower <= s.length() && s.length() <= upper; } + BoundTest(std::size_t l = 0, std::size_t u = 0) : lower(l), upper(u) {} + bool operator()(const std::string& s) + { + return lower <= s.length() && s.length() <= upper; + } private: std::size_t lower; @@ -35,13 +37,13 @@ class BoundTest int main() { - std::ifstream fin ("../data/storyDataFile.txt"); + std::ifstream fin("../data/storyDataFile.txt"); std::size_t quantity9 = 0, quantity10 = 0; BoundTest test9(1, 9); BoundTest test10(1, 10); - for (std::string word; fin >> word; ) { + for (std::string word; fin >> word;) { if (test9(word)) ++quantity9; if (test10(word)) ++quantity10; } diff --git a/ch14/ex14_40.cpp b/ch14/ex14_40.cpp index 1db417c1..7d94670c 100644 --- a/ch14/ex14_40.cpp +++ b/ch14/ex14_40.cpp @@ -4,7 +4,8 @@ C++ Primer 5th Exercise Answer Source Code Copyright (C) 2014-2015 github.com/pezy/Cpp-Primer -Rewrite the `biggies` function to use function-object classes in place of lambdas +Rewrite the `biggies` function to use function-object classes in place of +lambdas If you have questions, try to connect with me: pezy @@ -18,18 +19,25 @@ using std::vector; using std::string; #include -using std::cout; using std::endl; +using std::cout; +using std::endl; #include -using std::sort; using std::stable_sort; using std::for_each; +using std::sort; +using std::stable_sort; +using std::for_each; class ShorterString { public: - bool operator()(string const& s1, string const& s2) const { return s1.size() < s2.size(); } + bool operator()(string const& s1, string const& s2) const + { + return s1.size() < s2.size(); + } }; class BiggerEqual { size_t sz_; + public: BiggerEqual(size_t sz) : sz_(sz) {} bool operator()(string const& s) { return s.size() >= sz_; } @@ -45,24 +53,28 @@ string make_plural(size_t ctr, string const& word, string const& ending) return (ctr > 1) ? word + ending : word; } -void elimDups(vector &words) { +void elimDups(vector& words) +{ sort(words.begin(), words.end()); auto end_unique = unique(words.begin(), words.end()); words.erase(end_unique, words.end()); } -void biggies( vector &words, vector::size_type sz ) { +void biggies(vector& words, vector::size_type sz) +{ elimDups(words); stable_sort(words.begin(), words.end(), ShorterString()); auto wc = find_if(words.begin(), words.end(), BiggerEqual(sz)); auto count = words.end() - wc; - cout << count << " " << make_plural(count, "word", "s") << " of length " << sz << " or longer" << endl; + cout << count << " " << make_plural(count, "word", "s") << " of length " + << sz << " or longer" << endl; for_each(wc, words.end(), Print()); cout << endl; } int main() { - vector vec{ "fox", "jumps", "over", "quick", "red", "red", "slow", "the", "turtle"}; + vector vec{"fox", "jumps", "over", "quick", "red", + "red", "slow", "the", "turtle"}; biggies(vec, 4); } diff --git a/ch14/ex14_42.cpp b/ch14/ex14_42.cpp index 12ccb592..e1b7b815 100644 --- a/ch14/ex14_42.cpp +++ b/ch14/ex14_42.cpp @@ -8,15 +8,19 @@ int main() { using std::placeholders::_1; - std::vector ivec {1, 111, 1111, 11111}; - int count = std::count_if (ivec.cbegin(), ivec.cend(), std::bind(std::greater(), _1, 1024)); + std::vector ivec{1, 111, 1111, 11111}; + int count = std::count_if(ivec.cbegin(), ivec.cend(), + std::bind(std::greater(), _1, 1024)); std::cout << count << std::endl; - std::vector svec {"pooh", "pooh", "pezy", "pooh"}; - auto found = std::find_if (svec.cbegin(), svec.cend(), std::bind(std::not_equal_to(), _1, "pooh")); + std::vector svec{"pooh", "pooh", "pezy", "pooh"}; + auto found = + std::find_if(svec.cbegin(), svec.cend(), + std::bind(std::not_equal_to(), _1, "pooh")); std::cout << *found << std::endl; - std::transform(ivec.begin(), ivec.end(), ivec.begin(), std::bind(std::multiplies(), _1, 2)); + std::transform(ivec.begin(), ivec.end(), ivec.begin(), + std::bind(std::multiplies(), _1, 2)); for (int i : ivec) std::cout << i << " "; std::cout << std::endl; } diff --git a/ch14/ex14_43.cpp b/ch14/ex14_43.cpp index 426c3ed3..43e3e5a5 100644 --- a/ch14/ex14_43.cpp +++ b/ch14/ex14_43.cpp @@ -18,11 +18,11 @@ int main() { - auto data = { 2, 3, 4, 5 }; + auto data = {2, 3, 4, 5}; int input; std::cin >> input; std::modulus mod; - auto predicator = [&](int i){ return 0 == mod(input, i); }; + auto predicator = [&](int i) { return 0 == mod(input, i); }; auto is_divisible = std::any_of(data.begin(), data.end(), predicator); std::cout << (is_divisible ? "Yes!" : "No!") << std::endl; diff --git a/ch14/ex14_44.cpp b/ch14/ex14_44.cpp index 504614e3..f8c97ffe 100644 --- a/ch14/ex14_44.cpp +++ b/ch14/ex14_44.cpp @@ -7,7 +7,8 @@ ***************************************************************************/ //! //! Exercise 14.44: -//! Write your own version of a simple desk calculator that can handle binary operations. +//! Write your own version of a simple desk calculator that can handle binary +//! operations. //! #include @@ -22,49 +23,35 @@ int add(int i, int j) } //! named lambda -auto mod = [] (int i, int j) -{ - return i % j ; -}; +auto mod = [](int i, int j) { return i % j; }; //! functor -struct wy_div -{ - int operator ()(int denominator, int divisor) +struct wy_div { + int operator()(int denominator, int divisor) { - return denominator / divisor ; + return denominator / divisor; } }; - //! the map -std::map> binops = -{ - {"+", add}, // function pointer - {"-", std::minus()}, // library functor - {"/", wy_div()}, // user-defined functor - {"*", [] (int i, int j) { return i*j; }}, // unnamed lambda - {"%", mod} // named lambda object +std::map> binops = { + {"+", add}, // function pointer + {"-", std::minus()}, // library functor + {"/", wy_div()}, // user-defined functor + {"*", [](int i, int j) { return i * j; }}, // unnamed lambda + {"%", mod} // named lambda object }; - int main() { - while(true) - { + while (true) { std::cout << "\npleasr enter: num operator num :\n"; - int n1 , n2; std::string s; + int n1, n2; + std::string s; std::cin >> n1 >> s >> n2; - std::cout << binops[s] (n1, n2); + std::cout << binops[s](n1, n2); } return 0; } - - - - - - - diff --git a/ch14/ex14_45.cpp b/ch14/ex14_45.cpp index afcf2dee..40d502d1 100644 --- a/ch14/ex14_45.cpp +++ b/ch14/ex14_45.cpp @@ -1,18 +1,18 @@ #include "ex14_45.h" -Sales_data::Sales_data(std::istream &is) : Sales_data() +Sales_data::Sales_data(std::istream& is) : Sales_data() { is >> *this; } -Sales_data& Sales_data::operator+=(const Sales_data &rhs) +Sales_data& Sales_data::operator+=(const Sales_data& rhs) { units_sold += rhs.units_sold; revenue += rhs.revenue; return *this; } -std::istream& operator>>(std::istream &is, Sales_data &item) +std::istream& operator>>(std::istream& is, Sales_data& item) { double price = 0.0; is >> item.bookNo >> item.units_sold >> price; @@ -23,20 +23,21 @@ std::istream& operator>>(std::istream &is, Sales_data &item) return is; } -std::ostream& operator<<(std::ostream &os, const Sales_data &item) +std::ostream& operator<<(std::ostream& os, const Sales_data& item) { - os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " << item.avg_price(); + os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " + << item.avg_price(); return os; } -Sales_data operator+(const Sales_data &lhs, const Sales_data &rhs) +Sales_data operator+(const Sales_data& lhs, const Sales_data& rhs) { Sales_data sum = lhs; sum += rhs; return sum; } -Sales_data& Sales_data::operator=(const std::string &isbn) +Sales_data& Sales_data::operator=(const std::string& isbn) { *this = Sales_data(isbn); return *this; diff --git a/ch14/ex14_45.h b/ch14/ex14_45.h index d0576efc..50c4de8e 100644 --- a/ch14/ex14_45.h +++ b/ch14/ex14_45.h @@ -23,10 +23,13 @@ class Sales_data { friend Sales_data operator+(const Sales_data&, const Sales_data&); public: - Sales_data(const std::string &s, unsigned n, double p):bookNo(s),units_sold(n),revenue(n*p){} - Sales_data() : Sales_data("", 0, 0.0f){} - Sales_data(const std::string &s) : Sales_data(s, 0, 0.0f){} - Sales_data(std::istream &is); + Sales_data(const std::string& s, unsigned n, double p) + : bookNo(s), units_sold(n), revenue(n * p) + { + } + Sales_data() : Sales_data("", 0, 0.0f) {} + Sales_data(const std::string& s) : Sales_data(s, 0, 0.0f) {} + Sales_data(std::istream& is); Sales_data& operator=(const std::string&); Sales_data& operator+=(const Sales_data&); @@ -49,7 +52,7 @@ Sales_data operator+(const Sales_data&, const Sales_data&); inline double Sales_data::avg_price() const { - return units_sold ? revenue/units_sold : 0; + return units_sold ? revenue / units_sold : 0; } #endif diff --git a/ch14/ex14_49.cpp b/ch14/ex14_49.cpp index c585b0a3..ac6e3c7a 100644 --- a/ch14/ex14_49.cpp +++ b/ch14/ex14_49.cpp @@ -6,31 +6,32 @@ Date::Date(Size days) { //! calculate the year - Size y400 = days/YtoD_400; - Size y100 = (days - y400*YtoD_400)/YtoD_100; - Size y4 = (days - y400*YtoD_400 - y100*YtoD_100)/YtoD_4; - Size y = (days - y400*YtoD_400 - y100*YtoD_100 - y4*YtoD_4)/365; - Size d = days - y400*YtoD_400 - y100*YtoD_100 - y4*YtoD_4 - y*365; - this->year = y400*400 + y100*100 + y4*4 + y; + Size y400 = days / YtoD_400; + Size y100 = (days - y400 * YtoD_400) / YtoD_100; + Size y4 = (days - y400 * YtoD_400 - y100 * YtoD_100) / YtoD_4; + Size y = (days - y400 * YtoD_400 - y100 * YtoD_100 - y4 * YtoD_4) / 365; + Size d = days - y400 * YtoD_400 - y100 * YtoD_100 - y4 * YtoD_4 - y * 365; + this->year = y400 * 400 + y100 * 100 + y4 * 4 + y; //! check if leap and choose the months vector accordingly - std::vectorcurrYear - = isLeapYear(this->year) ? monthsVec_l : monthsVec_n; + std::vector currYear = + isLeapYear(this->year) ? monthsVec_l : monthsVec_n; //! calculate day and month using find_if + lambda Size D_accumu = 0, M_accumu = 0; - //! @bug fixed: the variabbles above hade been declared inside the find_if as static - //! which caused the bug. It works fine now after being move outside. + //! @bug fixed: the variabbles above hade been declared inside the + //! find_if as static + //! which caused the bug. It works fine now after being move + //! outside. - std::find_if(currYear.cbegin(), currYear.cend(), [&](Size m){ + std::find_if(currYear.cbegin(), currYear.cend(), [&](Size m) { D_accumu += m; - M_accumu ++; + M_accumu++; - if(d < D_accumu) - { - this->month = M_accumu; - this->day = d + m - D_accumu ; + if (d < D_accumu) { + this->month = M_accumu; + this->day = d + m - D_accumu; return true; } @@ -40,55 +41,52 @@ Date::Date(Size days) } //! construcotr taking iostream -Date::Date(std::istream &is, std::ostream &os) +Date::Date(std::istream& is, std::ostream& os) { is >> day >> month >> year; - if(is) - { - if(check(*this)) return; - else - { + if (is) { + if (check(*this)) + return; + else { os << "Invalid input! Object is default initialized."; *this = Date(); } } - else - { + else { os << "Invalid input! Object is default initialized."; *this = Date(); } - } //! copy constructor -Date::Date(const Date &d) : - day(d.day), month(d.month), year(d.year) -{} +Date::Date(const Date& d) : day(d.day), month(d.month), year(d.year) +{ +} //! move constructor -Date::Date(Date&& d) noexcept : - day(d.day), month(d.month), year(d.year) -{ std::cout << "copy moving";} +Date::Date(Date&& d) noexcept : day(d.day), month(d.month), year(d.year) +{ + std::cout << "copy moving"; +} //! copy operator= -Date &Date::operator= (const Date &d) +Date& Date::operator=(const Date& d) { - this->day = d.day; + this->day = d.day; this->month = d.month; - this->year = d.year; + this->year = d.year; return *this; } //! move operator= -Date &Date::operator =(Date&& rhs) noexcept +Date& Date::operator=(Date&& rhs) noexcept { - if(this != &rhs) - { - this->day = rhs.day; + if (this != &rhs) { + this->day = rhs.day; this->month = rhs.month; - this->year = rhs.year; + this->year = rhs.year; } std::cout << "moving ="; @@ -101,33 +99,34 @@ Date::Size Date::toDays() const Size result = this->day; //! check if leap and choose the months vector accordingly - std::vectorcurrYear - = isLeapYear(this->year) ? monthsVec_l : monthsVec_n; + std::vector currYear = + isLeapYear(this->year) ? monthsVec_l : monthsVec_n; //! calculate result + days by months - for(auto it = currYear.cbegin(); it != currYear.cbegin() + this->month -1; ++it) + for (auto it = currYear.cbegin(); it != currYear.cbegin() + this->month - 1; + ++it) result += *it; //! calculate result + days by years - result += (this->year/400) * YtoD_400; - result += (this->year%400/100) * YtoD_100; - result += (this->year%100/4) * YtoD_4; - result += (this->year%4) * YtoD_1; + result += (this->year / 400) * YtoD_400; + result += (this->year % 400 / 100) * YtoD_100; + result += (this->year % 100 / 4) * YtoD_4; + result += (this->year % 4) * YtoD_1; return result; } //! member operators: += -= -Date &Date::operator +=(Date::Size offset) +Date& Date::operator+=(Date::Size offset) { *this = Date(this->toDays() + offset); return *this; } -Date &Date::operator -=(Date::Size offset) +Date& Date::operator-=(Date::Size offset) { - if(this->toDays() > offset) + if (this->toDays() > offset) *this = Date(this->toDays() - offset); else *this = Date(); @@ -137,71 +136,59 @@ Date &Date::operator -=(Date::Size offset) //! non-member operators: << >> - == != < <= > >= -std::ostream& -operator <<(std::ostream& os, const Date& d) +std::ostream& operator<<(std::ostream& os, const Date& d) { os << d.day << " " << d.month << " " << d.year; return os; } -std::istream& -operator >>(std::istream& is, Date& d) +std::istream& operator>>(std::istream& is, Date& d) { - if(is) - { + if (is) { Date input = Date(is, std::cout); - if(check(input)) d = input; + if (check(input)) d = input; } return is; } - -int operator -(const Date &lhs, const Date &rhs) +int operator-(const Date& lhs, const Date& rhs) { return lhs.toDays() - rhs.toDays(); } - -bool operator ==(const Date &lhs, const Date &rhs) +bool operator==(const Date& lhs, const Date& rhs) { - return (lhs.day == rhs.day ) && - (lhs.month == rhs.month) && - (lhs.year == rhs.year ) ; + return (lhs.day == rhs.day) && (lhs.month == rhs.month) && + (lhs.year == rhs.year); } - -bool operator !=(const Date &lhs, const Date &rhs) +bool operator!=(const Date& lhs, const Date& rhs) { return !(lhs == rhs); } - -bool operator < (const Date &lhs, const Date &rhs) +bool operator<(const Date& lhs, const Date& rhs) { return lhs.toDays() < rhs.toDays(); } - -bool operator <=(const Date &lhs, const Date &rhs) +bool operator<=(const Date& lhs, const Date& rhs) { return (lhs < rhs) || (lhs == rhs); } - -bool operator >(const Date &lhs, const Date &rhs) +bool operator>(const Date& lhs, const Date& rhs) { return !(lhs <= rhs); } - -bool operator >=(const Date &lhs, const Date &rhs) +bool operator>=(const Date& lhs, const Date& rhs) { return !(lhs < rhs); } - -Date operator - (const Date &lhs, Date::Size rhs) -{ //! ^^^ rhs must not be larger than 2^32-1 +Date operator-(const Date& lhs, Date::Size rhs) +{ //! ^^^ rhs must not be larger than 2^32-1 //! copy lhs Date result(lhs); result -= rhs; @@ -209,9 +196,8 @@ Date operator - (const Date &lhs, Date::Size rhs) return result; } - -Date operator + (const Date &lhs, Date::Size rhs) -{ //! ^^^ rhs must not be larger than 2^32-1 +Date operator+(const Date& lhs, Date::Size rhs) +{ //! ^^^ rhs must not be larger than 2^32-1 //! copy lhs Date result(lhs); result += rhs; diff --git a/ch14/ex14_49.h b/ch14/ex14_49.h index 9be38d4f..3d33279d 100644 --- a/ch14/ex14_49.h +++ b/ch14/ex14_49.h @@ -6,8 +6,10 @@ ***************************************************************************/ //! //! Exercise 7.40: -//! Choose one of the following abstractions (or an abstraction of your own choosing). -//! Determine what data are needed in the class. Provide an appropriate set of constructors. +//! Choose one of the following abstractions (or an abstraction of your own +//! choosing). +//! Determine what data are needed in the class. Provide an appropriate set of +//! constructors. //! Explain your decisions. //! //! Exercise 14.5: @@ -46,7 +48,8 @@ //! Explain which types should be used as operands and why. //! //! Exercise 14.49: -//! Regardless of whether it is a good idea to do so, define a conversion to bool +//! Regardless of whether it is a good idea to do so, define a conversion to +//! bool //! for the class from the previous exercise. //! @@ -56,12 +59,12 @@ #include #include -class Date -{ - friend bool operator ==(const Date& lhs, const Date& rhs); - friend bool operator < (const Date &lhs, const Date &rhs); - friend bool check(const Date &d); - friend std::ostream& operator <<(std::ostream& os, const Date& d); +class Date { + friend bool operator==(const Date& lhs, const Date& rhs); + friend bool operator<(const Date& lhs, const Date& rhs); + friend bool check(const Date& d); + friend std::ostream& operator<<(std::ostream& os, const Date& d); + public: typedef std::size_t Size; @@ -70,9 +73,9 @@ class Date //! constructor taking Size as days explicit Date(Size days); //! constructor taking three Size - Date(Size d, Size m, Size y) : day(d), month(m), year(y) { } + Date(Size d, Size m, Size y) : day(d), month(m), year(y) {} //! constructor taking iostream - Date(std::istream &is, std::ostream &os); + Date(std::istream& is, std::ostream& os); //! copy constructor Date(const Date& d); @@ -80,133 +83,108 @@ class Date Date(Date&& d) noexcept; //! copy operator= - Date& operator= (const Date& d); + Date& operator=(const Date& d); //! move operator= - Date& operator= (Date&& rhs) noexcept; + Date& operator=(Date&& rhs) noexcept; //! destructor -- in this case, user-defined destructor is not nessary. - ~Date(){ std::cout << "destroying\n"; } + ~Date() { std::cout << "destroying\n"; } //! members - Size toDays() const; //not implemented yet. - Date& operator +=(Size offset); - Date& operator -=(Size offset); - explicit operator bool() { return (year<4000) ? true : false; } + Size toDays() const; // not implemented yet. + Date& operator+=(Size offset); + Date& operator-=(Size offset); + explicit operator bool() { return (year < 4000) ? true : false; } private: - Size day = 1; - Size month = 1; - Size year = 0; + Size day = 1; + Size month = 1; + Size year = 0; }; -static const Date::Size YtoD_400 = 146097; //365*400 + 400/4 -3 == 146097 -static const Date::Size YtoD_100 = 36524; //365*100 + 100/4 -1 == 36524 -static const Date::Size YtoD_4 = 1461; //365*4 + 1 == 1461 -static const Date::Size YtoD_1 = 365; //365 +static const Date::Size YtoD_400 = 146097; // 365*400 + 400/4 -3 == 146097 +static const Date::Size YtoD_100 = 36524; // 365*100 + 100/4 -1 == 36524 +static const Date::Size YtoD_4 = 1461; // 365*4 + 1 == 1461 +static const Date::Size YtoD_1 = 365; // 365 //! normal year -static const std::vector monthsVec_n = -{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; +static const std::vector monthsVec_n = {31, 28, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31}; //! leap year -static const std::vector monthsVec_l = -{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; +static const std::vector monthsVec_l = {31, 29, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31}; //! non-member operators: << >> - == != < <= > >= //! -std::ostream& -operator <<(std::ostream& os, const Date& d); -std::istream& -operator >>(std::istream& is, Date& d); -int -operator - (const Date& lhs, const Date& rhs); -bool -operator ==(const Date& lhs, const Date& rhs); -bool -operator !=(const Date& lhs, const Date& rhs); -bool -operator < (const Date& lhs, const Date& rhs); -bool -operator <=(const Date& lhs, const Date& rhs); -bool -operator >(const Date& lhs, const Date& rhs); -bool -operator >=(const Date& lhs, const Date& rhs); -Date -operator - (const Date& lhs, Date::Size rhs); -Date -operator +(const Date& lhs, Date::Size rhs); - - +std::ostream& operator<<(std::ostream& os, const Date& d); +std::istream& operator>>(std::istream& is, Date& d); +int operator-(const Date& lhs, const Date& rhs); +bool operator==(const Date& lhs, const Date& rhs); +bool operator!=(const Date& lhs, const Date& rhs); +bool operator<(const Date& lhs, const Date& rhs); +bool operator<=(const Date& lhs, const Date& rhs); +bool operator>(const Date& lhs, const Date& rhs); +bool operator>=(const Date& lhs, const Date& rhs); +Date operator-(const Date& lhs, Date::Size rhs); +Date operator+(const Date& lhs, Date::Size rhs); //! utillities: -bool check(const Date &d); -inline bool -isLeapYear(Date::Size y); - - - +bool check(const Date& d); +inline bool isLeapYear(Date::Size y); //! check if the date object passed in is valid - inline bool - check(const Date &d) - { - if(d.month==0 || d.month >12) - return false; - else - { - //! month == 1 3 5 7 8 10 12 - if(d.month==1 || d.month==3 || d.month==5 || d.month==7 || - d.month==8 || d.month==10|| d.month==12) - { - if(d.day==0 || d.day > 31) return false; - else +inline bool check(const Date& d) +{ + if (d.month == 0 || d.month > 12) + return false; + else { + //! month == 1 3 5 7 8 10 12 + if (d.month == 1 || d.month == 3 || d.month == 5 || d.month == 7 || + d.month == 8 || d.month == 10 || d.month == 12) { + if (d.day == 0 || d.day > 31) + return false; + else return true; - } - else - { - //! month == 4 6 9 11 - if(d.month==4 || d.month==6 || d.month==9 || d.month==11) - { - if(d.day==0 || d.day > 30) return false; - else - return true; - } - else - { - //! month == 2 - if(isLeapYear(d.year)) - { - if(d.day==0 || d.day >29) return false; - else - return true; - } - else - { - if(d.day==0 || d.day >28) return false; - else - return true; - } - } - } - } - } - - inline bool - isLeapYear(Date::Size y) - { - if (!(y%400)) - { - return true; - } - else - { - if(!(y%100)) - { - return false; - } - else - return !(y%4); - } - } + } + else { + //! month == 4 6 9 11 + if (d.month == 4 || d.month == 6 || d.month == 9 || d.month == 11) { + if (d.day == 0 || d.day > 30) + return false; + else + return true; + } + else { + //! month == 2 + if (isLeapYear(d.year)) { + if (d.day == 0 || d.day > 29) + return false; + else + return true; + } + else { + if (d.day == 0 || d.day > 28) + return false; + else + return true; + } + } + } + } +} + +inline bool isLeapYear(Date::Size y) +{ + if (!(y % 400)) { + return true; + } + else { + if (!(y % 100)) { + return false; + } + else + return !(y % 4); + } +} #endif // DATE_H diff --git a/ch14/ex14_49_TEST.cpp b/ch14/ex14_49_TEST.cpp index c83fbae2..bc2b4f6d 100644 --- a/ch14/ex14_49_TEST.cpp +++ b/ch14/ex14_49_TEST.cpp @@ -3,6 +3,5 @@ int main() { Date date(12, 4, 2015); - if (static_cast(date)) - std::cout << date << std::endl; + if (static_cast(date)) std::cout << date << std::endl; } diff --git a/generate_format_command.py b/generate_format_command.py new file mode 100644 index 00000000..bf44c679 --- /dev/null +++ b/generate_format_command.py @@ -0,0 +1,15 @@ +from sys import argv +from os import listdir +from os.path import isfile, join + +if len(argv) > 1: + mypath = argv[1] +else: + mypath = '.' + +print 'clang-format -i', + +onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath, f)) ] +for file in onlyfiles: + if (file.endswith(('.cpp', '.cc', '.h'))): + print mypath + '\\' + file,