第3章 標準庫型別 2

2021-06-01 11:00:35 字數 1815 閱讀 8181

3.2.3 string物件的操作

1. string的size和empty操作

string物件的長度指的是string物件中字元的個數,可以通過size操作獲取。

string str("anders");

cout << str.size() << endl;

empty()成員函式將返回bool值,如果string物件為空則返回true,否則返回false。

2. string::size_type型別

size操作返回的是string::size_type型別的值。

為了使用由string型別定義的size_type型別,程式設計師必須加上作用域操作符來說明使用的size_type型別是由string類定義的。

任何儲存string的size操作結果必須為string::size_type型別。特別重要的是,最好不要把size的返回值賦給乙個int變數。

3. string關係操作符

string物件比較操作是區分大小寫的,即同乙個字元的大小形式被認為是兩個不同的字元。在多數計算機上,大寫的字母位於小寫字母之前:任何乙個大寫字母都小於任意的小寫字母。

關係操作符比較兩個string物件時採用了(大小寫敏感的)字典排序相同的策略:

6. 和字串字面值的連線

string str1("ad");

string str2 = str1 + "da";

當進行string物件和字串字面值混合連線操作時,+操作符的左右運算元必須至少有乙個是string型別的。

string str1("ad");

string str2 = "ad" + "da"; //error c2110: '+' : cannot add two pointers

string str3 = str1 + " " + " ";

string str4 = " " + " " + str1; //error c2110: '+' : cannot add two pointers

7. 從string物件獲取字元

string str1("abcdefghijklmn");

for(string::size_type i = 0; i <= str1.size() - 1;i++)

8. 下標操作可用作左值

和變數一樣,string物件的下標操作返回值也是左值。

9. 計算下標值

任何可產生整型值的表示式都可用作下標操作符的索引。

string物件的索引變數最好也用string::size_type型別。

標準庫不要求檢查索引值,所用索引的下標越界是沒有定義的,這樣往往導致嚴重的執行時錯誤。

3.2.4 string物件中字元的處理

#include "stdafx.h"

#include #include #include using std::cout;

using std::endl;

using std::cin;

using std::string;

int main()

cout << num << endl;

}

通常需要知道某個特殊字元是否為空白字元、字母或數字。這些函式都在cctype標頭檔案中定義。

c標準庫標頭檔案形式為name.h,而c++版本則命名為cname,少了字尾.h而在頭檔名前加了c。c表示這個標頭檔案源自c標準庫。cname標頭檔案中定義的名字都定義在命名空間std內,而.h版本中的名字卻不是這樣。

第3章 標準庫型別

1.寫出string型別的五種初始化方法 string str string str value string str str2 string str n,c string str iterator1,iterator2 2.如何對string物件進行讀寫操作,如何讀入未知數目的string物件?i...

第3章 標準庫型別 3

3.3 標準庫vector型別 vector是同一種型別的物件的集合,每個物件都有乙個對應的資料索引值。和string物件一樣,標準庫將負責管理與儲存元素相關的記憶體。我們把vector稱作容器,是因為它可以包含其他物件。乙個容器中的所有物件都必須是同一種型別的。vector是乙個類模板 class...

第3章 標準庫型別 1

3.1 命名空間的using宣告 使用using宣告可以在不需要加字首namespace name 的情況下訪問命名空間中的名字。一旦使用了using宣告,我們就可以直接引用名字,而不需要再引用該名字的命名空間。include stdafx.h include using std cout usin...