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;
}

在這裏插入圖片描述

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