STL(Standard Template Library,标准模板库),从广义上讲分为三类:algorithm(算法)、container(容器)和iterator(迭代器),容器和算法通过迭代器可以进行无缝地连接。在C++标准中,STL被组织为下面的13个头文件:<algorithm>、<deque>、<functional>、<iterator>、<vector>、<list>、<map>、<memory>、<numeric>、<queue>、<set>、<stack> 和<utility>。
容器:容器的头文件包含算法部分主要由头文件<algorithm>,<numeric>和<functional>组 <deque>、<vector>、<list>、<map>、<queue>、<set>、<stack>
1.序列式容器(Sequence containers)
每个元素都有固定位置--取决于插入时机和地点,和元素值无关。有vector、deque、list (线性结构)
2.关联式容器(Associated containers)
元素位置取决于特定的排序准则,和插入顺序无关 有set、multiset、map、multimap(树形结构)
迭代器:迭代器作用类似于指针,用于部分容器的增删改查等功能。迭代器部分主要由头文件<utility>,<iterator>和<memory>组 成。
算法:算法部分主要由头文件<algorithm>,<numeric>和<functional>组成。<algorithm>现阶段用的最多,是由一大堆模版函数组成的,可以认为每个函数在很大程度上 都是独立的,其中常用到的功能范围涉及到比较、交换、查找、遍历操作、复制、修改、移除、反转、排序、合并等等。
以下是部分容器操作代码:
string容器:
#include <iostream>
#include <exception>
#include <string>
using namespace std;
void stringInit() //字符串初始化;
{
string s1;
string s2("hello world!");
string s3(10,'h');
string s4(s2);
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
}
void stringAt() //返回当前字符串中第n个字符,at()在越界时会抛出异常;
{
string s1("helloworld!");
//cout << s1[10000000] << endl;
try
{
cout << s1.at(20) << endl;
}
catch(exception &e)
{
cout << e.what() << endl;
}
}
void stringStr() //返回一个以'\0'结尾的字符串的首地址;
{
string s1("helloworld!");
const char *ptr = s1.c_str();
cout << ptr << endl;
}
void stringCopy() //拷贝字符串函数
{
string s1("helloworld!");
char buf[32] = {0};
s1.copy(buf,6,6);
cout << buf << endl;
}
void stringLength() //求字符串长度函数;
{
string s1("helloworld!");
cout << s1.length() << endl;
}
void stringEmpty() //判断字符串是否为空的函数;
{
string s1("helloworld!");
if(!s1.empty())
{
cout << s1<< endl;
}
}
void stringAssign() //字符串赋值函数;
{
string s1("helloworld!");
s1.assign("hello xly"); //当前字符串赋值;
cout << s1 << endl;
s1.assign("hello xly",5); //当前字符串的前5个字符赋值;
cout << s1 << endl;
s1.assign(10,'*'); //10个"*"赋值;
cout << s1 << endl;
s1.assign("hello xly",5,4); //字符串的第五个字符开始的四个字符赋值;
cout << s1 << endl;
}
void stringAppend()
{
string s1("helloworld!");
s1 += "and"; //"+="重载为字符串连接符号,将字符串添加到当前字符串结尾;
cout << s1 << endl;
string s2(" hello xly.");
s1.append(s2); //将s2添加到s1结尾;
cout << s1 << endl;
s2.append(10,'*'); //将10个"*"添加到s2结尾;
cout << s1 << endl;
s2.append(s1,11,3); //将是s1第11个字符后的三个字符添加到s1结尾;
cout << s2 << endl;
}
void stringCompare()
{
string s1("helloworld!");
string s2(" hello xly.");
cout <<s1.compare(s2) << endl; //字符串比较函数,返回值为1,0,-1,分别表示目标字符串s2比s1">","=","<";
cout << s1 << endl;
}
void stringSubstr()
{
string s1("helloworld!");
string s2(" hello xly.");
cout << s1.substr(5,6) << endl; //返回由pos开始的n个字符组成的子字符串
}
int main()
{
stringInit();
stringAt();
stringStr();
stringCopy();
stringLength();
stringEmpty();
stringAssign();
stringAppend();
stringCompare();
stringSubstr();
return 0;
}