STL是一个C++通用库,它主要又迭代器(iterators)、算法(algorithms)、容器(containers)、函数对象(function object)、内存分配器( allocators)和适配器(adapter)等六大部分组成。
STL 是标准化的组件,对于编程人员来说,标准化组件以为着可以直接使用这些现成的组件,而不用重新开发。STL现在是C++的一部分,因此不用额外安装,它被内建在编译器之内。使用STL最重要的就是掌握基本理论和编程方法,从而能够举一反三,下面通过对比来阐述STL的基本概念。
在传统的C++中,一般习惯使用数组和指针来进行数据的管理和分配,例子如下:
#include <cstdlib>
#include <iostream>
using namespace std;
int cmp ( const void *a , const void *b)
{
int aa = *(int *)a;
int bb = *(int *)b;
return (aa < bb) ? -1 : (aa > bb) ? 1 : 0;
}
int main (int argc , char *argcv[])
{
const int size = 10;
int array [size];
int n = 0;
cout << "please input 10 integers:" << endl;
while (cin >> array[n++] && (n <= (size - 1)));
qsort (array, n, sizeof(int), cmp);
cout << "output the 10 sorted integers:" << endl;
for (int i = 0; i < size; ++i)
{
cout << array[i] << " ";
}
}
上述代码的功能在于读取一整数序列并存入数组中,然后对该数组进行排序,最后把排序后的数组打印出来。
容器主要用于包含其他对象的类,就像数组,队列,堆栈等数据结构可以包含整数,小数,类等数据成员一样,最常见的容器模板类就是向量类(vector)。使用向量类和迭代器对上面的代码进行修改。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char const *argv[])
{
vector<int> v;
int input;
int n = 0;
cout << "Please input 10 intergers:" << endl;
while ((++n) && (n < 11))
{
cin >> input;
v.push_back(input);
}
sort (v.begin(), v.end());
n = v.size();
cout << "Output the 10 sorted integers:" << endl;
for (int i = 0; i < n; ++i)
{
cout << v[i] << " ";
}
}
在上面的例子中使用了vector和iterator技术。