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

转载于:https://www.cnblogs.com/wuyinfenghappy/p/7502121.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值