STL初步

这篇只介绍一些常用的STL及一些简单用法

更多请移步dalao博客

 

 

 

排序

sort(a,a+n)

 

a    ——首地址

a+n——尾地址

 

默认从小到大

bool cmp(int a,int b)
{
    return a<b;
}

 

可自行修改cmp

 

 

检索(lower_bound.  upper_bound)

lower_bound( begin,end,num)

 

从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字

找到返回该数字的地址,不存在则返回end

通过返回的地址减去起始地址begin,得到找到数字在数组中的下标

 

upper_bound( begin,end,num)

 

 

找的是第一个大于num的数字,其余一样

 

https://www.luogu.com.cn/problem/UVA10474

 

 

lower_bound 数组重载:

bool cmp(const int& a, const int& b)
{return a > b;}

 

 

 

 

lower_bound 结构体重载:

1. https://blog.csdn.net/qq_40642465/article/details/89339026?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

 

 

2. https://blog.csdn.net/qq_36876305/article/details/74713917

 

 

不定长数组:vector

首先vector是一个模版类,需要声明 (类似于int a[ ]  )

vector<int>a   

 

  

vector就是一个不定长数组(先进后出)

 

并且附带一些操作

 

//假设a为一个vector
a.size()                        //读取大小
 
a.resize()                     //改变大小

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

a.pop_back()               //删除尾部元素

 

 

集合:set

 

set就是数学意义上的集合

关联容器

内部封装红黑树

默认从小到大排序

 

 

常见用法

s.begin()            返回set容器的第一个元素

s.end()            返回set容器的最后一个元素

s.clear()             删除set容器中的所有的元素

s.empty()           判断set容器是否为空

s.insert()            插入一个元素

s.erase()             删除一个元素
 
s.size()           返回当前set容器中的元素个数

s.union()              并集

s.intersection()       交集

s.difference().        差集

 

 set的遍历

set<int>::iterator it; 
    set<int>::iterator it1; 
    for(it=po.begin();it!=po.end();it++) 
    
        for(it1=poo.begin();it1!=poo.end();it1++) 
            *it,*it1

 

 

set也支持upper_bound() lower_bound() find()等操作













 

 

 

 映射:map

map就是从键(key)到值(value)的映射

声明:

map<string,int> month

 

赋值

month["July "]=7;

这里的[ ]是重载过的

 

 

map中的find和count

count 返回的是被查找元素的个数。如果有,返回1;否则,返回0。注意,map中不存在相同元素,所以返回值只能是1或0。

使用find,返回的是被查找元素的位置(返回迭代器),没有则返回map.end()

 

 

 

 

 

stack&queue&priority_queue

 

栈和队列就不具体介绍了

去看这篇https://www.cnblogs.com/littlepage/p/12113748.html

 

 

优先队列

声明:

#include<vector>
#include<queue>

priority_queue<int,vector<int>,greater<int> >pq;//注意最后两个>>不要连起来

 

优先队列的出队方式不是queue的front(),而是top(),只出队不删除

 

posted @ 2020-02-27 21:54  juuich  阅读(55)  评论(0)    收藏  举报