深度分析C++string(上篇)

[复制链接]
发表于 2026-2-3 22:57:14 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
目次

前言
1.C++ string类
2.string类中的常见构造
3.string类对象的容量操纵
4.. string类对象的访问及遍历操纵
5. auto和范围for(增补)
auto关键字
范围for
竣事语


前言

   C语言我们学习了字符串和字符串的相干函数,在C语言中,字符串是以'\0'末了的一些字符的聚集,为了操纵方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP的头脑,而且底层空间必要用户本身管理,稍不注意大概还会越界访问。本日我们将正式步入C++ string类的学习。
  1.C++ string类

C++中的string类是STL的一个告急构成部分,它提供了对字符串的封装和处理处罚功能。 
在使用string类时,必须包罗#include头文件以及using namespace std;
下面是参考的官方链接 
http://www.cplusplus.com/reference/string/string/?kw=string
接下来,我们将进一步学习string类。
2.string类中的常见构造


  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main() {
  5.         string s1;
  6.         string s2("hello world");
  7.         string s3(6, 'x');
  8.         string s4(s3);
  9.         cout << s1 << endl;
  10.         cout << s2 << endl;
  11.         cout << s3 << endl;
  12.         cout << s4 << endl;
  13.         return 0;
  14. }
复制代码
 

3.string类对象的容量操纵

函数名称功能阐明
size(重点)返回字符串有用字符长度
length 返回字符串有用字符长度
capacity返回空间总大
  1. void string1() {
  2.         string s("I love you!!!");
  3.         cout << s.size() << endl;
  4.         cout << s.length() << endl;
  5.         cout << s.capacity() << endl;
  6.         cout << s << endl;
  7. }
复制代码
 

在C++的string类中,size()和length()成员函数返回的是字符串中字符的数量,不包罗末了的空字符(\0),由于string类内部管理内存时会自动在字符串末了添加一个空字符,但这个空字符不计入字符串的长度。
capacity()成员函数返回的是字符串当前分配的内存可以或许容纳的字符数量,这个值通常大于或便是size()的返回值,以容纳未来大概的字符添加操纵,而不会立即触发重新分配内存。
 


empty (重点)检测字符串开释为空串,是返回true,否则返回false
clear (重点)清空有用字符
reserve (重点)为字符串预留空间**
resize (重点)将有用字符的个数该成n个,多出的空间用字符c添补 

  1. void string1() {
  2.         string s("I love you!!!");
  3.         cout << s.size() << endl;
  4.         cout << s.length() << endl;
  5.         cout << s.capacity() << endl;
  6.         cout << s << endl;
  7.         // 使用empty()检查字符串是否为空
  8.         if (s.empty()) {
  9.                 cout << "s is empty." << endl;
  10.         }
  11.         else {
  12.                 cout << "s is not empty." << endl;
  13.         }
  14.         //s.clear();
  15.         //cout << s.size() << endl;
  16.         ///cout << s.capacity() << endl;
  17.         //cout << s << endl;
  18.         s.resize(18, 'a');
  19.         //s.resize(6);
  20.         cout << s.size() << endl;
  21.         cout << s.capacity() << endl;
  22.         cout << s << endl;
  23. }
复制代码

 可根据本身的需求自行更改代码。不难发现capacity 的巨细会根据字符串的巨细变革大概举行相应的变革,变革情况见上capacity的先容。linux下gcc和VS的capacity变革规则是略有差别的,各人可以下去实验下。
  1. void string2()
  2. {
  3.         string s;
  4.         // 测试reserve是否会改变string中有效元素个数
  5.         s.reserve(100);
  6.         cout << s.size() << endl;
  7.         cout << s.capacity() << endl;
  8.         // 测试reserve参数小于string的底层空间大小时,是否会将空间缩小
  9.         s.reserve(50);
  10.         cout << s.size() << endl;
  11.         cout << s.capacity() << endl; //输出原来值或更大,不会缩小
  12. }
复制代码
  1. void TestPushBack() {
  2.         string s;
  3.         size_t sz = s.capacity();
  4.         cout << "capacity: " << sz << '\n';
  5.         cout << "making s grow:\n";
  6.         for (int i = 0; i < 100; ++i)
  7.         {
  8.                 s.push_back('c');
  9.                 if (sz != s.capacity())
  10.                 {
  11.                         sz = s.capacity();
  12.                         cout << "capacity changed: " << sz << '\n';
  13.                 }
  14.         }
  15. }
复制代码
 

 当把\0加上时,我们会发现刚开始的变革是2倍,背面是1.5倍,这是VS本身规定的变革规则,刚开始会默认开设一个巨细为16字节的数组,背面变革的空间是在堆上的。
而gcc运行此代码都是2倍的变革。

注意:
   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不会改变容量巨细。
  
vs和g++下string布局的阐明(相识),小编也没有明确的通透。
注意:下述布局是在32位平台下举行验证,32位平台下指针占4个字节。
vs下string的布局 string统共占28个字节,内部布局稍微复杂一点,先是有一个团结体,团结体用来界说 string中字符串的存储空间:
当字符串长度小于16时,使用内部固定的字符数组来存放。 当字符串长度大于便是16时,从堆上开辟空间
    union _Bxty { // storage for small buffer or pointer to larger one
  value_type _Buf[_BUF_SIZE];
  pointer _Ptr;
  char _Alias[_BUF_SIZE];
  // to permit aliasing } _Bx;
  这种筹划也是有肯定原理的,大多数情况下字符串的长度都小于16,那string对象创建 好之后,内部已经有了16个字符数组的固定空间,不必要通过堆创建,服从高。
其次:另有一个size_t字段生存字符串长度,一个size_t字段生存从堆上开辟空间总的容量 末了:另有一个指针做一些其他事变。 故统共占16+4+4+4=28个字节。

g++下string的布局
G++下,string是通过写时拷贝实现的,string对象统共占4个字节,内部只包罗了一个 指针,该指针未来指向一块堆空间,内部包罗了如下字段:
空间总巨细 字符串有用长度 引用计数
指向堆空间的指针,用来存储字符串 

4.. string类对象的访问及遍历操纵


 




【】既可以访问字符又可以修改字符,非常的方便。
  1. void string3() {
  2.         string s1("I love you");
  3.         // 获取begin和end迭代器
  4.         std::string::iterator it = s1.begin();
  5.         std::string::iterator it_end = s1.end();
  6.         cout << s1[3] << endl;
  7.         s1[1] = 'u';
  8.         cout << s1 << endl;
  9.         cout << *it << endl; // 输出 I,因为it指向第一个字符
  10.         cout << *(it_end-1) << endl;
  11.         }
复制代码

 上面是正向迭代器的使用,另有一个反向迭代器
  1. std::string::reverse_iterator it = s1.rbegin();
  2. std::string::reverse_iterator it_end = s1.rend();
复制代码
接下来我们通过迭代器来实现字符串的遍历
  1. void string4() {
  2.         string s("I love you!");
  3.         // 获取begin和end迭代器
  4.         string::iterator it = s.begin();
  5.         string::reverse_iterator it1 = s.rbegin();
  6.         while (it != s.end()) {
  7.                 cout << *it << " " ;
  8.                 ++it;
  9.         }
  10.         cout << '\n';
  11.         while (it1 != s.rend()) {
  12.                 cout << *it1 << " " ;
  13.                 ++it1; // 移动到下一个字符(实际上是前一个字符)
  14.         }
  15.        
  16. }
复制代码
 

C++11之后,直接使用auto界说迭代器,让编译器推到迭代器的范例
  1. void string4() {
  2.         string s("I love you!");
  3.        
  4.         // 获取begin和end迭代器
  5.         //string::iterator it = s.begin();
  6.         auto it = s.begin();
  7.         //string::reverse_iterator it1 = s.rbegin();
  8.         auto it1 = s.rbegin();
  9.         while (it != s.end()) {
  10.                 cout << *it << " " ;
  11.                 ++it;
  12.         }
  13.         cout << '\n';
  14.         while (it1 != s.rend()) {
  15.                 cout << *it1 << " " ;
  16.                 ++it1; // 移动到下一个字符(实际上是前一个字符)
  17.         }
  18. }
复制代码
范围for
  1.         for (auto ch : s){
  2.                 cout << ch << endl;
  3. }
复制代码
5. auto和范围for(增补)

auto关键字

在这里增补2个C++11的小语法。
在早期C/C++中auto的寄义是:使用auto修饰的变量,是具有自动存储器的局部变量,厥后这个 不告急了。C++11中,标准委员会变废为宝赋予了auto全新的寄义即:auto不再是一个存储范例 指示符,而是作为一个新的范例指示符来指示编译器,auto声明的变量必须由编译器在编译时期 推导而得。
用auto声明指针范例时,用auto和auto*没有任何区别,但用auto声明引用范例时则必须加&
当在同一行声明多个变量时,这些变量必须是雷同的范例,否则编译器将会报错,由于编译器现实 只对第一个范例举行推导,然后用推导出来的范例界说其他变量。
auto不能作为函数的参数,可以做返回值,但是发起审慎使用
auto不能直接用来声明数组
   // 编译报错:error C3538: 在声明符列表中,“auto”必须始终推导为同一范例
auto cc = 3, dd = 4.0;
// 编译报错:error C3318: “auto []”: 数组不能具有此中包罗“auto”的元素范例
auto array[] = { 4, 5, 6 };

  1. #include <iostream>
  2. using namespace std;
  3. int func1()
  4. {
  5.         return 10;
  6. }
  7. // 不能做参数
  8. void func2(auto a)
  9. {}
  10. // 可以做返回值,但是建议谨慎使用
  11. auto func3()
  12. {
  13.         return 3;
  14. }
  15. int main() {
  16.         return 0;
  17. }
复制代码


  1. #include <iostream>
  2. using namespace std;
  3. int func1()
  4. {
  5.         return 10;
  6. }
  7. int main() {
  8.         int a = 10;
  9.         auto b = a;
  10.         auto c = 'a';
  11.         auto d = func1();
  12.         // 编译报错:rror C3531: “e”: 类型包含“auto”的符号必须具有初始值设定项
  13.         //auto e;
  14.         cout << typeid(b).name() << endl;
  15.         cout << typeid(c).name() << endl;
  16.         cout << typeid(d).name() << endl;
  17.         int x = 10;
  18.         auto y = &x;
  19.         auto* z = &x;
  20.         auto& m = x;
  21.         cout << typeid(x).name() << endl;
  22.         cout << typeid(y).name() << endl;
  23.         cout << typeid(z).name() << endl;
  24.         return 0;
  25. }
复制代码
 着实对于auto的真正常用的用法是用于迭代器方面,让编译器本身推导迭代器范例,对于复杂的迭代器范例可以简化代码。
下面展示的代码为扩展,别处拷贝过来。
  1. #include<iostream>
  2. #include <string>
  3. #include <map>
  4. using namespace std;
  5. int main()
  6. {
  7.         std::map<std::string, std::string> dict = { { "apple", "苹果" },{ "orange",
  8.    "橙子" }, {"pear","梨"} };
  9.         // auto的用武之地
  10.    //std::map<std::string, std::string>::iterator it = dict.begin();
  11.         auto it = dict.begin();
  12.         while (it != dict.end())
  13.         {
  14.                 cout << it->first << ":" << it->second << endl;
  15.                 ++it;
  16.         }
  17.                 return 0;
  18. }
复制代码
  std::map<std::string, std::string> dict = { { "apple", "苹果" },{ "orange", "橙子" }, {"pear","梨"} };:界说一个std::map对象dict,它包罗三个键值对,键是std::string范例的字符串,值也是std::string范例的字符串。
  范围for

对于一个有范围的聚集而言,由步调员来阐明循环的范围是多余的,偶然候还会容易犯错误。因此 C++11中引入了基于范围的for循环。
for循环后的括号由冒号“ :”分为两部分:第一部分是范围 内用于迭代的变量,第二部分则体现被迭代的范围,自动迭代,自动取数据,自动判断竣事。
范围for可以作用到数组和容器对象上举行遍历
范围for的底层很简单,容器遍历现实就是更换为迭代器,这个从汇编层也可以看到。
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main() {
  5.         int arr[] = { 1,2,3,4,5 };
  6.         for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
  7.                 arr[i] *= 2;
  8.         }
  9.         for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
  10.                 cout << arr[i] << endl;
  11.         }
  12.         // C++11的遍历
  13.         for (auto &e : arr) {
  14.                 e *= 2;
  15.         }
  16.         for (auto e : arr) {
  17.                 cout << e << endl;
  18.         }
  19.         string s("hello world!");
  20.         for (auto it : s) {
  21.                 cout << it << " " ;
  22.         }
  23.         return 0;
  24. }
复制代码
 


竣事语

   本期教学就到此竣事了,下节我们将继续扩展string的其他接口和函数。
  末了感谢各位友友的支持,友友们点个赞吧!!! 
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表