目录

上图是C++官网对于string的解释:string是表示字符序列的对象。
string本质是一个类,位于std的命名空间下,使用前需要包含头文件#include
简单理解,string可以看做一个存放字符的顺序表(容器就是数据结构,顺序表就是一种数据结构)。

迭代器是一个对象,主要用于访问容器中的元素,类似于访问数组的指针。
迭代器的实现体现了C++语言面向对象特性中的封装,避免了我们直接遍历容器中的数据。
string迭代器的定义:
- string s("hello string");
- string::iterator it = s.begin();//正向迭代器
- string::const_iterator it2 = s.cbegin();//const正向迭代器
- string::reverse_iterator it3 = s.rbegin();//反向迭代器
- string::const_reverse_iterator it4 = s.crbegin();//const反向迭代器
🥝普通对象及const对象的正向遍历
普通对象:
- string s("hello string");//普通对象
- string::iterator it1 = s.begin();
- *it1 = 'x';//可以改变
- while (it1 != s.end())
- {
- cout << *it1;//类似指针的解引用
- ++it1;//类似++指针
- }
- cout << endl;

const对象:
- string::const_iterator it2 = s.cbegin();//const正向迭代器
- //*it2 = 'H';//err
- while (it2 != s.cend())
- {
- cout << *it2;
- ++it2;
- }
- cout << endl;

🥝普通对象及const对象的反向遍历
普通对象:
- string::reverse_iterator it3 = s.rbegin();//反向迭代器
- *it3 = 'G';//ok
- while (it3 != s.rend())
- {
- cout << *it3;
- ++it3;
- }
- cout << endl;

const对象:
- string::const_reverse_iterator it4 = s.crbegin();//const反向迭代器
- //*it4 = 'G';//err
- while (it4 != s.crend())
- {
- cout << *it4;
- ++it4;
- }
- cout << endl;

迭代器的定义那么一长串,我们有auto关键字可以偷懒:

auto可以自动推断变量类型,那如果我们全写成auto,恰好又没有代码提示:

可读性就变得非常差!所以在前期尽量不要使用auto,还是提高提高自己的代码熟练度为好!

string有七种构造函数:
string()默认构造:构造空串


string(const char* s)用常量字符串构造

string(const string& str)拷贝构造

string (const string& str, size_t pos, size_t len = npos)拷贝构造str的子串,从str的pos位置开始拷贝,拷贝长度为len的子串

len给了一个缺省参数npos,什么是npos呢?

npos的类型是size_t,即无符号类型的整形,值为-1。-1的补码是32个1,转化为无符号数,就是整形的最大值2^32-1
问题来了,如果我们不给len的长度,或者给的len超过了常量字符串的长度,vs编译器会不会开出更大的空间呢?

答案是不会!我们可以看到:当len<=常量字符串长度时,size和len的值是一样的;当len>常量字符串长度时,size顶多到常量字符串长度的位置。
Linux系统下,g++编译器对于size的处理也是一样的,但是对于capacity的处理不像vs编译器会多开点空间。

string(const char*s,size_t n)构造常量字符串的子串,子串的长度为n

注意这里的n,如果大于常量字符串的长度,编译器会不会开出更大的空间呢?
vs编译器:


g++:

答案是会的! 只不过多开的空间里存放的数据内容我们是不清楚的。
string (size_t n, char c);用n个字符c构造

template <class InputIterator> string (InputIterator first, InputIterator last)范围构造:从主串的first位置到last位置构造子串
由于运用到了模板,根据模板自动识别类型生成对应的构造函数的特性,传入的参数可以是迭代器或者是指针:
①迭代器


②指针


注:迭代器传参的时候编译器会检查越界,用指针的时候不会,所以用指针的时候不要越界访问!