STL = Standard Template Library,标准模板库,惠普实验室开发的一系列软件的统称。它是由Alexander Stepanov、Meng Lee和David R Musser在惠普实验室工作时所开发出来的。这可能是一个历史上最令人兴奋的工具的最无聊的术语。从根本上说,STL是一些“容器”的集合,这些“容器”有list,vector,set,map等,STL也是算法和其他一些组件的集合。这里的“容器”和算法的集合指的是世界上很多聪明人很多年的杰作。STL的目的是标准化组件,这样就不用重新开发,可以使用现成的组件。STL现在是C++的一部分,因此不用额外安装什么。
-------摘自百度百科
STL常用到的头文件:
<span style="font-size:18px;">#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>//算法
#include <queue>//队列
#include <map>
#include <deque>//双端队列
#include <vector>
#include <stack>//栈
#include <iterator>//迭代器</span>
priority_queue模板类有三个模板参数,下面介绍两种:
//元素类型
priority_queue<int>q;
//容器类型
//1.从小到大排列
priority_queue<int,vector<int>,greater<int> >q;
//2.从大到小排列
priority_queue<int,vector<int>,less<int> >q;
优先队列,使用示例:
priority_queue<int,vector<int>,greater<int> >q;
for(int i=0;i<10;i++)
{
scanf("%d",&a);
q.push(a);
}
while(!q.empty())
{
x = q.top();
q.pop();
if(q.empty())
break;
printf("%d ",x);
}
如上述代码,若输入:1,5,4,7,2,9,8,3,10,6这随机排列的是个数
输出时,直接就会输出:1,2,3,4,5,6,7,8,9,10
若定义的时候,把greater换做less,
输出时,直接就会输出:10,9,8,7,6,5,4,3,2,1
这就是我理解的优先队列的好处(PS:可能还有别的,如果我知道我会再加)。
q.push(a);即将a压入优先队列q,压入之后也是会直接到按顺序应该在的位置。
访问优先队列的队首元素 q.top() ;
出队列: q.pop();
入队列: q.push(x);
判断优先队列是否为空: q.empty();
(以下的map,跟set来自会神)
二、map
map是键-值对的集合。map类型通常可理解为关联数组。
一个字典树的经典题,用字典树写的,要大概90行,用map只要40就够了,
没错,map就是这么的好用,
map的头文件 :#include<map>;
map对象的定义:
map<string,int>q;
map<int,int>q;
map<string,node>q;
map<int,node>;
map<int,string>q;
map添加元素:
如:
map<int,string>q;
q[100]=”adnsnd”;
//还可以:
q.insert(pair<int,string>(100,”adnsnd”));
q.insert(map<int,string>::value_type(100,”adnsnd”)) ;
map查找并读取元素:
如map<int,string>q;
最简单的方法:int n=q[“dadad”];
q.count(x); 返回q中x出现的次数。
判断q中x是否出现过可以这样:
if(q.find(x)==q.end()) //x在没有在q中出现过。
使用迭代器判断:
map<int,string>::iterator it=q.find(x);
if(it!=q.end()) //x在q中出现过。
map中删除元素:
q.erase(x)//删除q中键为x的元素。返回size_type类型的值,表示删除的元素的个数。
map对象的迭代遍历:
map<int,string>::const_iterator it=q.begin();
While(it!=q.end())
{
printf(“%d %d\n”,it-first,it-second);
it++;
}
三、set
头文件:#include<set>
set对象的定义:set<int>ivec;
set中添加元素:
ivec.insert(10);
set中获取元素
ivec.find(x);
判断x是否在ivec中出现过可以用:
ivec.find(x);
也可以用 ivec.count(x);
这里count的返回值只能是1或0。
set的遍历;
set<int>::iterator it=ivec.begin();
While(it!=q.end())
{
printf(“%d ”,*it);
it++;}
set的删除元素:
it=ivec.find(x);
ivec.erase(it);
set 的lower_bound/upper_bound的用法:
使用迭代器 set<int>::iterator itlow,itup;
itlow=ivec.lower_bound(x);
itup=ivec.upper_bound(x);
lower_bound返回的是在ivec中大于或等于x的第一个数的位置,
upper_bound返回的是在ivec中大于x的第一个数的位置;