string之size/capacity/reserve/resize/clear/empty/max_size/shring_of_fit函数

对string的capacity和size的操作函数

  • size()函数和length()函数的结果相同,都是返回字符串有效字符的长度,都不包含最后的’\0’,底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致。
  • capacity函数返回当前string的预留空间的大小。
  • max_size()输出一个字符串最多有多长,输出为定值,在Win32的编译环境下是42亿九千万多,即2的32次方。
  • reserve()方法为string预留空间,不改变有效元素的大小,当reserve的参数小于string的底层空间的从大小时,reserve不会改变容量的大小。
  • resize(size_t n)和resize(size_t n, char c)函数不仅改变size的大小,也改变capacity的大小。后者会用C来填充多出来的元素空间。**注意:**如果元素个数增多,可能会改变底层容量的大小,如果将元素个数减少,底层容量的总空间大小不变。
  • clear会将string的元素清空,size置为0,但capacity的大小不变。
  • empty():如果str的size为0,返回真,否则,返回假。
  • shrink_to_fit():将str的容量收缩到合适的大小,该函数没有参数。

代码:

/*
>Plan:string
>Author:ADiiana
>Time:2019/03/17
*/

#include<iostream>
#include<string>
using namespace std;

int main(){

	string str("Test string");
	cout << str << endl;
	cout << "str.size(): " << str.size() << endl;
	cout << "str.length(): " << str.length() << endl;
	cout << "str.capacity(): " << str.capacity() << endl;

	//cout << str[13] << endl;		//编译出错:访问超过size的元素为越界访问

	cout << "Win32:str.max_size(): " << str.max_size() << endl;		//win32的编译环境
	cout << "----------------------------------" << endl;

	cout << "capacity增大到100" << endl;
	str.reserve(100);						//reserve函数的用法;
	cout << "	str.size(): " << str.size() << endl;
	cout << "	str.capacity(): " << str.capacity() << endl;

	cout << "capacity缩小到10" << endl;
	str.reserve(10);
	cout << "	str.size(): " << str.size() << endl;
	cout << "	str.capacity(): " << str.capacity() << endl;

	cout << "----------------------------------" << endl;

	size_t sz = str.size();
	str.resize(sz + 2, '+');	//将str扩容到sz+2个字符,并用+填充
	cout << "size扩大到 sz + 2, 并用+填充" << endl;
	cout << str << endl;
	cout << "	str.size(): " << str.size() << endl;
	cout << "	str.capacity(): " << str.capacity() << endl << endl;

	str.resize(4);		//将str的大小改变为4个字符
	cout << "size 改变为 4: " << endl;
	cout << str << endl;
	cout << "	str.size(): " << str.size() << endl;
	cout << "	str.capacity(): " << str.capacity() << endl;

	cout << "----------------------------------" << endl;
	str.clear();
	cout << "clear之后:" << endl;
	cout << "	str.size(): " << str.size() << endl;
	cout << "	str.capacity(): " << str.capacity() << endl;

	if (str.empty()){
		cout << "str is empty..." << endl;
	}
	else{
		cout << "str is not empty..." << endl;
	}

	cout << "----------------------------------" << endl;
	str.resize(20);
	str.shrink_to_fit();
	cout << "shrink_to_fit: " << endl;
	cout << "	str.size(): " << str.size() << endl;
	cout << "	str.capacity(): " << str.capacity() << endl;

	system("pause");
	return 0;
}

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章