一。什么是STL?
-STL,即:Standard Template Library,是C++的一部分
-STL是常用数据结构和算法的集合
-STL的目标是标准化组件,提高开发效率和程序可靠性
二。STL主要由以下3个部分组成
-容器:管理数据的集合
-算法:处理集合内的元素
-迭代器:遍历集合内的元素
1.STL:里面的容器
容器里存放的都是值而不是引用
容器内部实施的是值拷贝操作。
容器中可以存放指针作为数据元素
2.线性表的典型操作
size:获取当前容器中的元素数目
insert:在当前元素前插入新元素
erase:删除当前元素
empty:判断当前容器是否为空
front:获取第一个元素
back:获取最后一个元素
3.vector的使用
#include <cstdlib> #include <iostream> #include <vector> using namespace std; int main(int argc, char *argv[]) { vector<int> vi(10); cout << "vi.size:" <<vi.size() <<endl; for(int i=0;i<5;i++) { vi[i] = i + 1; } vi.resize(8); cout << "Elements in vi" <<endl; for(int i=0;i<vi.size();i++) { cout << vi[i] <<endl; } vector <int> vin; vin = vi; vi.resize(0); cout << "Elements in vin:"<< endl; for(int i=0;i<vin.size();i++) { cout <<vin[i] <<endl; } cout << "Press the enter key to continue ..."; cin.get(); return EXIT_SUCCESS; }
4.STL中的容器
队列性质:先进先出
void queueUsage() { queue <double> q; for(int i=0;i<5;i++) { q.push(i/100.0); } cout <<"Elemets is " <<endl; while(!q.empty()) { double v = q.front(); q.pop(); cout << v <<endl; } }
输出结果 0 0.01 0.02 0.03 0.04
栈队列性质:后进先出
#include <cstdlib> #include <iostream> #include <stack> #include <queue> using namespace std; void StackUsage() { cout <<"Stack Usage "<< endl; stack <double> s; for(int i=0;i<5;i++) { s.push(i/100.0); } cout <<"Elemets is " <<endl; while(!s.empty()) { double v = s.top(); s.pop(); cout << v <<endl; } } int main(int argc, char *argv[]) { StackUsage(); cout << "Press the enter key to continue ..."; cin.get(); return EXIT_SUCCESS; }
输出结果0.04,0.03 ,0.02,0.01,0