STL用法总结

来源:互联网 发布:网络老歌曲大全100首 编辑:程序博客网 时间:2024/09/21 06:22

lower_bound

lower_bound的作用是查找“大于或者等于x的第一个位置”

【用法】

 int p=lower_bound(a,a+n,x)-a'


不定长数组:vector

【用法】

vector<string>a,vector<int>a;定义一个不定长的数组

a.size()  读取大小

a.resize()  改变大小

a.push_back()  向尾部添加元素

a.pop_back()  删除最后一个元素

eg.vector<int>pile[maxn]  相当于一个二维数组,一维固定,二维不固定


集合:set

每个元素最多只出现一次,默认从大到小排序

set<string>::iterator iterator是一个迭代器,类似于指针

eg 

for(set<string>::iterator it=dict.beigin();it!=dict.end();++it)

cout<<*it<<"\n"


映射 map

map就是从键(key)到值(value)的映射,例如可以用一个map<string,int>month_name来表示“月份名字到月份编号”,然后用month["july"]=7,这样来赋值

M.count(k)是返回m中k出现的次数。

set和map二者都支持insert,find,count,remove操作,并且可以按照从小到大的顺序循环遍历其中的元素,map还提供了[]运算符,是的map可以像数组一样使用,map也别称为“关联数组


栈 stack

【用法】

stack<int>s

s.push() 入栈

s.pop() 出栈

s.top() 取栈顶元素


队列  queue

【用法】

queue<int>q

q.push() 入队

q.pop()  出队

q.front() 取栈顶元素


优先队列 priority_queue<int>pq

由于出队的元素并不是最先进队的元素,出队方法由front(),变成top();

自定义类型也可以组成优先队列

例如,实现一个“个位数大的整数优先级反而小”的优先队列,可以定义一个结构体cmp,重载“()”运算符

struct cmp{

bool operator ( )  (const int a,const int b) const{

return a%10>b%10;

}

}

priority_queue<int,vector<int>,cmp>pq;

STL提供了更方便地方法

priority_queue<int,vector<int>,greater<int> >pq;


结构体 struct

结构体重载运算符

struct Node{    int p,d;    friend bool operator < (Node x,Node y)    {        if(x.p!=y.p)            return x.p>y.p;        else            return x.d>y.d;    }}stone[maxn],temp;priority_queue<Node>q;


0 0
原创粉丝点击