9 STL
9.1标准模板库
三大编程理念:过程化编程、对象化编程和泛型编程。标准模板库STL运用的就是泛型编程的思想,将算法独立于数据类型之外,强调了代码的重用技术。
STL是每一个C++程序员必须掌握的技术,其分为3部分:容器、迭代器、算法。
容器是存放同类数据的一种数据结构,如数组、队列、链表等。容器可以分为3大类:顺序容器、关联容器、容器适配器。迭代器用来遍历容器中的对象。算法是对容器对象的各种操作,如插入、删除、搜索、排序等。
9.2顺序容器
顺序容器包括string、vector、array、deque、list等。
9.2.1 string
标准库string可以用来存储不定长度的字符串,使用string需要包含头文件string和使用名称空间std。
//string初始化
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char ** argv)
{
//简单的初始化
string s1; //s1初始化为空字符串
string s2("hello"); //s2用C-风格字符串来初始化,等价于string s2 = "hello"
char ar[] = { "array"};
string s3(ar); //s3用字符数组来初始化,等价于string s3 = ar
const char * cp = "character pointer";
string s4(cp); //s4用字符指针来初始化,等价于string s4 = cp
string s5(s2); //s5用string对象来初始化,等价于string s5 = s2
//初始化进阶
string s6(5, 'a'); //用5个字符'a'来初始化s6
string s7("hello world",5); //取前5个字符来初始化s7
string s8(s4,10,7); //从s4的下标10开始,拷贝7个字符
string s9(s8.begin(), s8.end());//用s8的迭代器来初始化s9
cout << s1 << endl << s2 << endl << s3 << endl << s4 << endl << s5 << endl << s6 << endl << s7 << endl << s8 << endl << s9 << endl;
return 0;
}
运行结果:
hello
array
character pointer
hello
aaaaa
hello
pointer
pointer
在以前的string类中,介绍了6种方法来初始化string对象,在这里又介绍3种。我们学习了类,知道string本质上是一个类,其初始化时调用string的构造函数。那么string s2("hello")和string s2 = "hello"又有什么区别呢?
string s2("hello")是调用string的有参构造函数,string s2 = "hello"调用的是string类的拷贝构造函数。2种方法都可以用来初始化string对象,但是为了统一,以后都采用第一种方法。
//string迭代器
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char ** argv)
{
string s1("hello");
s1 += " world!";
string::iterator start = s1.begin();
string::iterator end = s1.end();
for (; start != end; start++)
{
cout << *start;
}
cout<< endl;
const string s2("hello China!");//字符串只读
string