马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
目次
前言
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类中的常见构造
- #include <iostream>
- #include <string>
- using namespace std;
- int main() {
- string s1;
- string s2("hello world");
- string s3(6, 'x');
- string s4(s3);
- cout << s1 << endl;
- cout << s2 << endl;
- cout << s3 << endl;
- cout << s4 << endl;
- return 0;
- }
复制代码
3.string类对象的容量操纵
函数名称功能阐明
size(重点)返回字符串有用字符长度
length 返回字符串有用字符长度
capacity返回空间总大
- void string1() {
- string s("I love you!!!");
- cout << s.size() << endl;
- cout << s.length() << endl;
- cout << s.capacity() << endl;
- cout << s << endl;
- }
复制代码
在C++的string类中,size()和length()成员函数返回的是字符串中字符的数量,不包罗末了的空字符(\0),由于string类内部管理内存时会自动在字符串末了添加一个空字符,但这个空字符不计入字符串的长度。
capacity()成员函数返回的是字符串当前分配的内存可以或许容纳的字符数量,这个值通常大于或便是size()的返回值,以容纳未来大概的字符添加操纵,而不会立即触发重新分配内存。
empty (重点)检测字符串开释为空串,是返回true,否则返回false
clear (重点)清空有用字符
reserve (重点)为字符串预留空间**
resize (重点)将有用字符的个数该成n个,多出的空间用字符c添补
- void string1() {
- string s("I love you!!!");
- cout << s.size() << endl;
- cout << s.length() << endl;
- cout << s.capacity() << endl;
- cout << s << endl;
- // 使用empty()检查字符串是否为空
- if (s.empty()) {
- cout << "s is empty." << endl;
- }
- else {
- cout << "s is not empty." << endl;
- }
- //s.clear();
- //cout << s.size() << endl;
- ///cout << s.capacity() << endl;
- //cout << s << endl;
- s.resize(18, 'a');
- //s.resize(6);
- cout << s.size() << endl;
- cout << s.capacity() << endl;
- cout << s << endl;
- }
复制代码
可根据本身的需求自行更改代码。不难发现capacity 的巨细会根据字符串的巨细变革大概举行相应的变革,变革情况见上capacity的先容。linux下gcc和VS的capacity变革规则是略有差别的,各人可以下去实验下。
- void string2()
- {
- string s;
- // 测试reserve是否会改变string中有效元素个数
- s.reserve(100);
- cout << s.size() << endl;
- cout << s.capacity() << endl;
- // 测试reserve参数小于string的底层空间大小时,是否会将空间缩小
- s.reserve(50);
- cout << s.size() << endl;
- cout << s.capacity() << endl; //输出原来值或更大,不会缩小
- }
复制代码- void TestPushBack() {
- string s;
- size_t sz = s.capacity();
- cout << "capacity: " << sz << '\n';
- cout << "making s grow:\n";
- for (int i = 0; i < 100; ++i)
- {
- s.push_back('c');
- if (sz != s.capacity())
- {
- sz = s.capacity();
- cout << "capacity changed: " << sz << '\n';
- }
- }
- }
复制代码
当把\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类对象的访问及遍历操纵
【】既可以访问字符又可以修改字符,非常的方便。
- void string3() {
- string s1("I love you");
- // 获取begin和end迭代器
- std::string::iterator it = s1.begin();
- std::string::iterator it_end = s1.end();
- cout << s1[3] << endl;
- s1[1] = 'u';
- cout << s1 << endl;
- cout << *it << endl; // 输出 I,因为it指向第一个字符
- cout << *(it_end-1) << endl;
- }
复制代码
上面是正向迭代器的使用,另有一个反向迭代器
- std::string::reverse_iterator it = s1.rbegin();
- std::string::reverse_iterator it_end = s1.rend();
复制代码 接下来我们通过迭代器来实现字符串的遍历
- void string4() {
- string s("I love you!");
- // 获取begin和end迭代器
- string::iterator it = s.begin();
- string::reverse_iterator it1 = s.rbegin();
- while (it != s.end()) {
- cout << *it << " " ;
- ++it;
- }
- cout << '\n';
- while (it1 != s.rend()) {
- cout << *it1 << " " ;
- ++it1; // 移动到下一个字符(实际上是前一个字符)
- }
-
- }
复制代码
C++11之后,直接使用auto界说迭代器,让编译器推到迭代器的范例
- void string4() {
- string s("I love you!");
-
- // 获取begin和end迭代器
- //string::iterator it = s.begin();
- auto it = s.begin();
- //string::reverse_iterator it1 = s.rbegin();
- auto it1 = s.rbegin();
- while (it != s.end()) {
- cout << *it << " " ;
- ++it;
- }
- cout << '\n';
- while (it1 != s.rend()) {
- cout << *it1 << " " ;
- ++it1; // 移动到下一个字符(实际上是前一个字符)
- }
- }
复制代码 范围for
- for (auto ch : s){
- cout << ch << endl;
- }
复制代码 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 };
- #include <iostream>
- using namespace std;
- int func1()
- {
- return 10;
- }
- // 不能做参数
- void func2(auto a)
- {}
- // 可以做返回值,但是建议谨慎使用
- auto func3()
- {
- return 3;
- }
- int main() {
- return 0;
- }
复制代码
- #include <iostream>
- using namespace std;
- int func1()
- {
- return 10;
- }
- int main() {
- int a = 10;
- auto b = a;
- auto c = 'a';
- auto d = func1();
- // 编译报错:rror C3531: “e”: 类型包含“auto”的符号必须具有初始值设定项
- //auto e;
- cout << typeid(b).name() << endl;
- cout << typeid(c).name() << endl;
- cout << typeid(d).name() << endl;
- int x = 10;
- auto y = &x;
- auto* z = &x;
- auto& m = x;
- cout << typeid(x).name() << endl;
- cout << typeid(y).name() << endl;
- cout << typeid(z).name() << endl;
- return 0;
- }
复制代码 着实对于auto的真正常用的用法是用于迭代器方面,让编译器本身推导迭代器范例,对于复杂的迭代器范例可以简化代码。
下面展示的代码为扩展,别处拷贝过来。
- #include<iostream>
- #include <string>
- #include <map>
- using namespace std;
- int main()
- {
- std::map<std::string, std::string> dict = { { "apple", "苹果" },{ "orange",
- "橙子" }, {"pear","梨"} };
- // auto的用武之地
- //std::map<std::string, std::string>::iterator it = dict.begin();
- auto it = dict.begin();
- while (it != dict.end())
- {
- cout << it->first << ":" << it->second << endl;
- ++it;
- }
- return 0;
- }
复制代码 std::map<std::string, std::string> dict = { { "apple", "苹果" },{ "orange", "橙子" }, {"pear","梨"} };:界说一个std::map对象dict,它包罗三个键值对,键是std::string范例的字符串,值也是std::string范例的字符串。
范围for
对于一个有范围的聚集而言,由步调员来阐明循环的范围是多余的,偶然候还会容易犯错误。因此 C++11中引入了基于范围的for循环。
for循环后的括号由冒号“ :”分为两部分:第一部分是范围 内用于迭代的变量,第二部分则体现被迭代的范围,自动迭代,自动取数据,自动判断竣事。
范围for可以作用到数组和容器对象上举行遍历
范围for的底层很简单,容器遍历现实就是更换为迭代器,这个从汇编层也可以看到。
- #include <iostream>
- #include <string>
- using namespace std;
- int main() {
- int arr[] = { 1,2,3,4,5 };
- for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
- arr[i] *= 2;
- }
- for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
- cout << arr[i] << endl;
- }
- // C++11的遍历
- for (auto &e : arr) {
- e *= 2;
- }
- for (auto e : arr) {
- cout << e << endl;
- }
- string s("hello world!");
- for (auto it : s) {
- cout << it << " " ;
- }
- return 0;
- }
复制代码
竣事语
本期教学就到此竣事了,下节我们将继续扩展string的其他接口和函数。
末了感谢各位友友的支持,友友们点个赞吧!!!
|