C++primer 14.3.1节练习

练习14.16

 1 #include <iostream>
 2 #include <string>
 3 #include <utility>
 4 #include <memory>
 5 #include <algorithm>
 6 
 7 using namespace std;
 8 
 9 class String {
10     friend ostream &operator<<(ostream &os, String &s);
11     friend bool operator==(const String& lhs, const String& rhs);
12     friend bool operator!=(const String& lhs, const String& rhs);
13 public:
14     String() : element(nullptr), first_free(nullptr) {}
15     String(char *);
16 private:
17     static allocator<char> alloc;
18     char *element;
19     char *first_free;
20 };
21 
22 allocator<char> String::alloc;
23 bool operator==(const String& lhs, const String& rhs);
24 bool operator!=(const String& lhs, const String& rhs);
25 
26 int main()
27 {
28     String s1;
29     String s2("ello");
30     String s3("hello world");
31     cout << s1;
32     cout << s2;
33     cout << s3;
34     cout << (s2 == s3);
35     cout << endl;
36     system("pause");
37     return 0;
38 }
39 
40 String::String(char *s)
41 {
42     int i = 0;
43     while (s[i] != '\0')
44         ++i;
45     auto newloc = alloc.allocate(i);
46     auto dest = newloc;
47     for (auto count = 0; count != i;++count)
48         alloc.construct(dest++, s[count]);
49     element = newloc;
50     first_free = dest;
51 }
52 
53 ostream & operator<<(ostream &os, String &s)
54 {
55     while (s.element != s.first_free)
56     {
57         os << *(s.element);
58         s.element++;
59     }
60     cout << endl;
61     return os;
62     // TODO: 在此处插入 return 语句
63 }
64 
65 ostream &operator<<(ostream &os, bool b);
66 
67 bool operator==(const String & lhs, const String & rhs)
68 {
69     auto i = lhs.element;
70     auto j = rhs.element;
71     if ((lhs.first_free - lhs.element) != (rhs.first_free - rhs.element))
72         return false;
73     while ((i != lhs.first_free) && (j != rhs.first_free))
74         if (*(i++) != *(j++))
75             return false;
76 }
77 
78 bool operator!=(const String & lhs, const String & rhs)
79 {
80     return !(lhs == rhs);
81 }

这段代码不知道为何结果不对,实在找不出来错误在哪。

 1 bool operator==(const StrVec & lhs, const StrVec & rhs)
 2 {
 3     auto i = lhs.elements;
 4     auto j = rhs.elements;
 5     if (lhs.size() == rhs.size())
 6     {
 7         while (i != lhs.first_free)
 8         {
 9             if (*i == *j)
10             {
11                 ++i;
12                 ++j;
13             }
14         }
15         return true;
16     }
17     else
18         return false;
19 }

类似的代码放在StrVec类中是正确的。

练习14.17

posted @ 2017-09-10 20:26  五月份小姐  阅读(261)  评论(0编辑  收藏  举报