当前位置:   article > 正文

c++初阶知识——string类详解

c++初阶知识——string类详解
 

目录

 

前言:

1.标准库中的string类

1.1 auto和范围for

auto

 范围for

1.2 string类常用接口说明

1.string类对象的常见构造

1.3 string类对象的访问及遍历操作

1.4. string类对象的修改操作 

 1.5 string类非成员函数

2.string类的模拟实现 

2.1 经典的string类问题 

2.2 浅拷贝 

2.3 深拷贝 

2.4 string类实现 

3.写时拷贝 


前言:

C语言中,字符串是以'\0'结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列
的库函数,但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户
自己管理,稍不留神可能还会越界访问。

1.标准库中的string类

在使用string类时,必须包含#include头文件以及using namespace std;

1.1 auto和范围for

auto

(1)在早期C/C++中auto的含义是:使用auto修饰的变量,是具有自动存储器的局部变量后来这个不重要了。C++11中,标准委员会变废为宝赋予了auto全新的含义即:auto不再是一个存储类型指示符,而是作为一个新的类型指示符来指示编译器,auto声明的变量必须由编译器在编译时期
推导而得

(2)用auto声明指针类型时,用auto和auto*没有任何区别,但用auto声明引用类型时则必须加&

(3)当在同一行声明多个变量时,这些变量必须是相同的类型,否则编译器将会报错,因为编译器实际只对第一个类型进行推导,然后用推导出来的类型定义其他变量

(4)auto不能作为函数的参数,可以做返回值,但是建议谨慎使用

(5)auto不能直接用来声明数组

  1. #include <map>
  2. using namespace std;
  3. int main()
  4. {
  5. std::map<std::string, std::string> dict = { { "apple", "苹果" },{ "orange",
  6. "橙子" }, {"pear","梨"} };
  7. // auto的用武之地
  8. //std::map<std::string, std::string>::iterator it = dict.begin();
  9. auto it = dict.begin();
  10. while (it != dict.end())
  11. {
  12. cout << it->first << ":" << it->second << endl;
  13. ++it;
  14. }
  15. 范围for
  16. 对于一个有范围的集合而言,由程序员来说明循环的范围是多余的,有时候还会容易犯错误。因此
  17. C++11中引入了基于范围的for循环。for循环后的括号由冒号“ :”分为两部分:第一部分是范围
  18. 内用于迭代的变量,第二部分则表示被迭代的范围,自动迭代,自动取数据,自动判断结束。
  19. 范围for可以作用到数组和容器对象上进行遍历
  20. 范围for的底层很简单,容器遍历实际就是替换为迭代器,这个从汇编层也可以看到。
  21. 2.3 string类的常用接口说明(注意下面我只讲解最常用的接口)
  22. 1. string类对象的常见构造
  23. return 0;
  24. }

 范围for

(1)对于一个有范围的集合而言,由程序员来说明循环的范围是多余的,有时候还会容易犯错误。因此C++11中引入了基于范围的for循环。for循环后的括号由冒号“ :”分为两部分:第一部分是范围内用于迭代的变量,第二部分则表示被迭代的范围,自动迭代,自动取数据,自动判断结束。

(2)范围for可以作用到数组和容器对象上进行遍历

(3)范围for的底层很简单,容器遍历实际就是替换为迭代器,这个从汇编层也可以看到。

示例:

  1. #include<iostream>
  2. #include <string>
  3. #include <map>
  4. using namespace std;
  5. int main()
  6. {
  7.    int array[] = { 1, 2, 3, 4, 5 };
  8.    // C++98的遍历
  9.    for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
  10.   {
  11.        array[i] *= 2;
  12.   }
  13.    for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
  14.   {
  15.        cout << array[i] << endl;
  16.   }
  17.    // C++11的遍历
  18.    for (auto& e : array)
  19.        e *= 2;
  20.    for (auto e : array)
  21.        cout << e << " " << endl;
  22.    string str("hello world");
  23.    for (auto ch : str)
  24.   {
  25.        cout << ch << " ";
  26.   }
  27.    cout << endl;
  28. return 0;
  29. }

1.2 string类常用接口说明

1.string类对象的常见构造

注意:
1. size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接
口保持一致,一般情况下基本都是用size()。


2. clear()只是将string中有效字符清空,不改变底层空间大小。


3. resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不
同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char
c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数
增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。


4. reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参
数小于string的底层空间总大小时,reserver不会改变容量大小。 

1.3 string类对象的访问及遍历操作

1.4. string类对象的修改操作 

注意
1. 在string尾部追加字符时,s.push_back(c) / s.append(1, c) / s += 'c'三种的实现方式差
不多,一般情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可
以连接字符串。


2. 对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留
好。 

 1.5 string类非成员函数

2.string类的模拟实现 

2.1 经典的string类问题 

上面已经对string类进行了简单的介绍,大家只要能够正常使用即可。在面试中,面试官总喜欢让
学生自己来模拟实现string类,最主要是实现string类的构造、拷贝构造、赋值运算符重载以及析
构函数。大家看下以下string类的实现是否有问题?

  1. // 为了和标准库区分,此处使用String
  2. class String
  3. {
  4. public:
  5. /*String()
  6. :_str(new char[1])
  7. {*_str = '\0';}
  8. */
  9. //String(const char* str = "\0") 错误示范
  10. //String(const char* str = nullptr) 错误示范
  11. String(const char* str = "")
  12. {
  13. // 构造String类对象时,如果传递nullptr指针,可以认为程序非
  14. if (nullptr == str)
  15. {
  16. assert(false);
  17. return;
  18. }
  19. _str = new char[strlen(str) + 1];
  20. strcpy(_str, str);
  21. }
  22. ~String()
  23. {
  24. if (_str)
  25. {
  26. delete[] _str;
  27. _str = nullptr;
  28. }
  29. }
  30. private:
  31. char* _str;
  32. };
  33. // 测试
  34. void TestString()
  35. {
  36. String s1("hello bit!!!");
  37. String s2(s1);
  38. }

 

说明:上述String类没有显式定义其拷贝构造函数与赋值运算符重载,此时编译器会合成默认
的,当用s1构造s2时,编译器会调用默认的拷贝构造。最终导致的问题是,s1、s2共用同一块内存空间,在释放时同一块空间被释放多次而引起程序崩溃,这种拷贝方式,称为浅拷贝。 

2.2 浅拷贝 

浅拷贝:也称位拷贝,编译器只是将对象中的值拷贝过来。如果对象中管理资源,最后就会导致
多个对象共享同一份资源,当一个对象销毁时就会将该资源释放掉,而此时另一些对象不知道该
资源已经被释放,以为还有效,所以当继续对资源进项操作时,就会发生发生了访问违规。

就像一个家庭中有两个孩子,但父母只买了一份玩具,两个孩子愿意一块玩,则万事大吉,万一
不想分享就你争我夺,玩具损坏。

所以可以采用深拷贝解决浅拷贝问题,即:每个对象都有一份独立的资源,不要和其他对象共享。父母给每个孩子都买一份玩具,各自玩各自的就不会有问题了。 

2.3 深拷贝 

 如果一个类中涉及到资源的管理,其拷贝构造函数、赋值运算符重载以及析构函数必须要显式给
出。一般情况都是按照深拷贝方式提供。

 

 

2.4 string类实现 

 能否写好string反映出我们对类和对象知识的理解是否深刻,这一块知识如果理解得不够深刻,我们的c++程序就会经常出现此类问题。为了方便管理,我们将string的实现分为3个文件是实现:

string.h :

  1. #pragma once
  2. #include<iostream>
  3. #include<assert.h>
  4. using namespace std;
  5. namespace Myobject
  6. {
  7. class string
  8. {
  9. public:
  10. typedef char* iterator;
  11. typedef const char* const_iterator;
  12. string& operator+=(char ch);
  13. string& operator+=(const char* str);
  14. void append(const char* str);
  15. void insert(size_t pos, char ch);
  16. void insert(size_t pos, const char* str);
  17. void erase(size_t pos, size_t len = npos);
  18. size_t find(char ch, size_t pos);
  19. size_t find(const char* str, size_t pos);
  20. string substr(size_t pos, size_t len);
  21. string& operator=(const string& s);
  22. string(const char* str = "")
  23. {
  24. _size = strlen(str);
  25. _capacity = _size;
  26. _str = new char[_capacity + 1];
  27. strcpy(_str, str);
  28. }
  29. string(const string& s)
  30. {
  31. _str = new char[s._capacity + 1];
  32. strcpy(_str, s._str);
  33. _size = s._size;
  34. _capacity = s._capacity;
  35. }
  36. void test0_01();
  37. void reserve(size_t n);
  38. void push_back(char ch);
  39. /*string()
  40. :_str(new char[1] {'\0'})
  41. ,_size(0)
  42. ,_capacity(0)
  43. {}*/
  44. iterator begin()
  45. {
  46. return _str;
  47. }
  48. iterator end()
  49. {
  50. return _str + _size;
  51. }
  52. const_iterator begin() const
  53. {
  54. return _str;
  55. }
  56. const_iterator end() const
  57. {
  58. return _str + _size;
  59. }
  60. const char* c_str() const
  61. {
  62. return _str;
  63. }
  64. size_t size()
  65. {
  66. return _size;
  67. }
  68. size_t capacity()
  69. {
  70. return _capacity;
  71. }
  72. char& operator[](size_t pos)
  73. {
  74. assert(pos < _size);
  75. return _str[pos];
  76. }
  77. const char& operator[](size_t pos) const
  78. {
  79. assert(pos < _size);
  80. return _str[pos];
  81. }
  82. ~string()
  83. {
  84. delete[] _str;
  85. _str = nullptr;
  86. _size = _capacity = 0;
  87. }
  88. private:
  89. char* _str;
  90. size_t _size;
  91. size_t _capacity;
  92. static const size_t npos;
  93. };
  94. ostream& operator<<(ostream& out, const string& s);
  95. istream& operator>>(istream& in, string& s);
  96. }

string.cpp :

  1. #define _CRT_SECURE_NO_WARNINGS 1
  2. #include"string.h"
  3. namespace Myobject
  4. {
  5. const size_t string::npos = -1;
  6. string string::substr(size_t pos, size_t len)
  7. {
  8. assert(pos < _size);
  9. if (len > _size - pos)
  10. {
  11. len = _size - pos;
  12. }
  13. string sub;
  14. sub.reserve(len);
  15. for (size_t i = 0; i < len; i++)
  16. {
  17. sub += _str[pos + i];
  18. }
  19. return sub;
  20. }
  21. size_t string::find(char ch, size_t pos)
  22. {
  23. assert(pos < _size);
  24. for (size_t i = 0; i < _size; i++)
  25. {
  26. if (_str[i] == ch)
  27. {
  28. return i;
  29. }
  30. }
  31. return npos;
  32. }
  33. size_t string::find(const char* str, size_t pos)
  34. {
  35. assert(pos < _size);
  36. const char* ptr = strstr(_str + pos, str);
  37. if (ptr == nullptr)
  38. {
  39. return npos;
  40. }
  41. else
  42. {
  43. return ptr - _str;
  44. }
  45. }
  46. void string::erase(size_t pos, size_t len)
  47. {
  48. assert(pos < _size);
  49. if (len >= _size - pos)
  50. {
  51. _str[pos] = '0';
  52. _size = pos;
  53. }
  54. else
  55. {
  56. for (size_t i = pos + len; i < _size; i++)
  57. {
  58. _str[i - len] = _str[i];
  59. }
  60. _size -= len;
  61. }
  62. }
  63. void string::insert(size_t pos, char ch)
  64. {
  65. assert(pos <= _size);
  66. if (_size == _capacity)
  67. {
  68. reserve(_capacity == 0 ? 4 : _capacity * 2);
  69. }
  70. size_t end = _size + 1;
  71. if (end > pos)
  72. {
  73. _str[end] = _str[end - 1];
  74. end--;
  75. }
  76. _str[pos] = ch;
  77. _size++;
  78. }//插入单个字符
  79. void string::insert(size_t pos, const char* str)
  80. {
  81. assert(pos <= _size);
  82. size_t len = strlen(str);
  83. if (len + _size > _capacity)
  84. {
  85. reserve(len + _size == 2 * _capacity ? len + _size : 2 * _capacity);
  86. }
  87. size_t end = _size + len;
  88. while (end - 2 > pos)
  89. {
  90. _str[end] = _str[end - len];
  91. end--;
  92. }
  93. for (int i = 0; i < len; i++)
  94. {
  95. _str[pos + i] = str[i];
  96. }
  97. _size += len;
  98. }
  99. void string::append(const char* str)
  100. {
  101. size_t len = strlen(str);
  102. if (len + _size > _capacity)
  103. {
  104. reserve(len + _size == 2 * _capacity ? len + _size : 2 * _capacity);
  105. }
  106. strcpy(_str + _size, str);
  107. _size += len;
  108. // _str[_size] = '\0';
  109. }
  110. string& string::operator+=(const char* str)
  111. {
  112. append(str);
  113. return *this;
  114. }
  115. void string::reserve(size_t n)
  116. {
  117. if (n > _capacity)
  118. {
  119. char* tmp = new char[n + 1];
  120. strcpy(tmp, _str);
  121. delete[] _str;
  122. _str = tmp;
  123. _capacity = n;
  124. }
  125. }//扩容
  126. void string::push_back(char ch)
  127. {
  128. if (_size == _capacity)
  129. {
  130. reserve(_capacity == 0 ? 4 : _capacity * 2);
  131. }
  132. _str[_size] = ch;
  133. _size++;
  134. _str[_size] = '\0';
  135. }//尾插
  136. string& string::operator+=(char ch)
  137. {
  138. push_back(ch);
  139. return *this;
  140. }
  141. string& string::operator=(const string& s)
  142. {
  143. if (this != &s)
  144. {
  145. delete[] _str;
  146. _str = new char[s._capacity + 1];
  147. strcpy(_str, s._str);
  148. _size = s._size;
  149. _capacity = s._capacity;
  150. return *this;
  151. }
  152. }
  153. ostream& operator<<(ostream& out, const string& s)
  154. {
  155. for (auto ch : s)
  156. {
  157. out << ch;
  158. }
  159. return out;
  160. }
  161. istream& operator>>(istream& in, string& s)
  162. {
  163. char ch;
  164. ch = in.get();
  165. while (ch != ' ' && ch != '\n')
  166. {
  167. s += ch;
  168. ch = in.get();
  169. }
  170. return in;
  171. }
  172. }

test.cpp :

  1. #define _CRT_SECURE_NO_WARNINGS 1
  2. #include"string.h"
  3. namespace Myobject
  4. {
  5. void test_01()
  6. {
  7. string s1;
  8. string s2("hello world");
  9. cout << s1.c_str() << endl;
  10. cout << s2.c_str() << endl;
  11. for (int i = 0; i < s2.size(); i++)
  12. {
  13. s2[i] += 2;
  14. }
  15. cout << s2.c_str() << endl;
  16. s2 += 'A';
  17. s2 += 'B';
  18. string::iterator it = s2.begin();
  19. while (it != s2.end())
  20. {
  21. cout << *it << " ";
  22. it++;
  23. }
  24. cout << endl;
  25. for (auto ch : s2)
  26. {
  27. cout << ch << " ";
  28. }
  29. cout << endl;
  30. s2.insert(0, '$');
  31. for (auto ch : s2)
  32. {
  33. cout << ch << " ";
  34. }
  35. cout << endl;
  36. s2.insert(8, "%%%%%%%");
  37. for (auto ch : s2)
  38. {
  39. cout << ch << " ";
  40. }
  41. cout << endl;
  42. s2.erase(8, 100);
  43. for (auto ch : s2)
  44. {
  45. cout << ch << " ";
  46. }
  47. cout << endl;
  48. /*s2.append("hehe");
  49. for (auto ch : s2)
  50. {
  51. cout << ch << " ";
  52. }
  53. s2 += "hello";
  54. for (auto ch : s2)
  55. {
  56. cout << ch << " ";
  57. }*/
  58. }
  59. void test02()
  60. {
  61. string s1("hello world");
  62. string s2 = s1.substr(6, 5);
  63. cout << s2.c_str() << endl;
  64. string s3("hello bit");
  65. s2 = s3;
  66. cout << s1 << endl;
  67. cout << s2 << endl;
  68. cin >> s1;
  69. cout << s1 << endl;
  70. }
  71. }
  72. int main()
  73. {
  74. Myobject::test02();
  75. //Myobject::test_01();
  76. return 0;
  77. }

3.写时拷贝 

写时拷贝就是一种拖延症,是在浅拷贝的基础之上增加了引用计数的方式来实现的。
引用计数:用来记录资源使用者的个数。在构造时,将资源的计数给成1,每增加一个对象使用该
资源,就给计数增加1,当某个对象被销毁时,先给该计数减1,然后再检查是否需要释放资源,
如果计数为1,说明该对象时资源的最后一个使用者,将该资源释放;否则就不能释放,因为还有
其他对象在使用该资源。

本章完。 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/919421
推荐阅读
相关标签
  

闽ICP备14008679号