string : 管理字符串,字符的容器,专门存放字符的动态顺序表
string类中变量 :size capacity 字符
string类中为了提高性能,才类中提供了一个长度为16个字符大小的数组,因为存放 \0 所以capacity是15
string类对象的容量操作
size 返回字符串有效字符长度
length 返回字符串有效字符长度
capacity 返回空间总大小
empty 检测字符串释放为空串,是返回true,否则返回false
clear 清空有效字符
reserve 为字符串预留空间**
resize 将有效字符的个数该成n个,多出的空间用字符c填充
reserve:
1. 扩容函数,只扩容不会改变有效元素个数
2. reserve(n),只有当n > string类对象底层空间容量时才会扩容
3. reserve(n),当n < string类对象底层空间容量时,reserve会忽略本次操作,除非n < 15
4.reserva一般只会把容量扩大,而不会缩小
5.VS中扩容方式是1.5倍
void Test1()
{
string s("hello");
cout << s << endl;
cout << s.size() << endl;
cout << s.capacity() << endl;
s.reserve(20);
cout << s << endl;
cout << s.size() << endl;
cout << s.capacity() << endl;
s.reserve(32);
cout << s << endl;
cout << s.size() << endl;
cout << s.capacity() << endl;
s.reserve(10);
cout << s << endl;
cout << s.size() << endl;
cout << s.capacity() << endl;
}
resize:
resize(size_t n):将string中有效字符个数改变到n个,多出的字符用0进行填充
resize(newsize, ch): 假设string类的有效元素个数为size,容量为capacity
1. newsize < size: 只是将有效元素个数改变到newsize即可,不会缩小容量
2. size<newsize<capacity: 直接将有效元素个数增加到newsize,多出的newsize-size个元素使用ch(0)进行填充
3. newsize > capacity: 扩容-:申请新空间,拷贝元素,释放旧空间--将新元素个数增加到newsize个,多出的newsize-size个元素使用ch(0)进行填充
void Test2()
{
string s("hello");
cout << s.size() << endl;
cout << s.capacity() << endl;
s.resize(10,'!');
cout << s << endl;
cout << s.size() << endl;
cout << s.capacity() << endl;
s.resize(20,'!');
cout << s << endl;
cout << s.size() << endl;
cout << s.capacity() << endl;
s.resize(30,'!');
cout << s << endl;
cout << s.size() << endl;
cout << s.capacity() << endl;
s.resize(40,'!');
cout << s << endl;
cout << s.size() << endl;
cout << s.capacity() << endl;
s.resize(30);
cout << s << endl;
cout << s.size() << endl;
cout << s.capacity() << endl;
s.resize(20);
cout << s << endl;
cout << s.size() << endl;
cout << s.capacity() << endl;
s.resize(10);
cout << s << endl;
cout << s.size() << endl;
cout << s.capacity() << endl;
}
注意:
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不会改变容量大小。