1. Sort函数,sort函数不仅可以对STL中的容器进行排序,还可对数组排序。如:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool comp(int a,int b){return a<b;}; 自定义排序函数
int main()
{
int a[5]={5,3,6,3,1};
sort(a,a+5,comp); 第二个参数是数组最后位置指针再加1,这一定要注意
for(int i=0;i<5;i++)
{
cout<<a[i]<<endl;
}
}
2. accumulate函数 (#include <numeric>)
Copy
template<class InputIterator, class Type>
Type accumulate(
InputIterator _First,
InputIterator _Last,
Type _Val
);
template<class InputIterator, class Type, class BinaryOperation>
Type accumulate(
InputIterator _First,
InputIterator _Last,
Type _Val,
BinaryOperation _Binary_op
);
Firtst,last ,val分别是起始位置,结束位置+1,初始值,以及自定义函数,
#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
using namespace std;
bool comp(int a,int b){return a<b;};
int mul(int a,int b){return a*b;};
int main()
{
int a[5]={5,3,6,3,1};
sort(a,a+5);
int sum=accumulate(a,a+5,1,mul);
cout<<sum<<endl;
}
3. reverse(v.begin(),v.en());反向排列第一个参数到第二个参数之前的元素
4. set实现了红黑树的平衡二叉检索树,插入元素时会自动排列,确保根节点大于左节点而小于右节点,而且保证左右子树平衡,不会插入相同键值的元素,会采取忽略处理,set是中序遍历,所以遍历输出后就是从小到大的值,检索速度高于vector,list,deque,不能直接修改set中的键值
set<int>::iterator it;
it=s.find(5); //找到就返回具体位置的迭代器,否则返回s.end()
4.1自定义set中的比较函数,使用比较结构体,重载()操作符
#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
#include <set>
using namespace std;
bool comp(int a,int b){return a<b;};
int mul(int a,int b){return a*b;};
struct Comp
{
bool operator()(int a,int b)
{
return a>b; ///从大到小排列
}
};
int main()
{
int a[5]={5,3,6,3,1};
//sort(a,a+5);
int sum=accumulate(a,a+5,1,mul);
//cout<<sum<<endl;
//set<int> s;
set<int,Comp>s;
for(int i=0;i<5;i++)
{
s.insert(a[i]);
}
set<int,Comp>::iterator it;
for(it=s.begin();it!=s.end();it++)
cout<<*it<<endl;
//it=s.find(4);
}
5. multiset与set的不同在于multiset可以插入键值重复的元素
6. Map的元素由一个键值和一个映照数据组成,也是平衡二叉树,插入时比较键值,键值不允许重复
Map<string,float> m;
m.insert(pair<string,float>(“Jack”,67));
m[“Jack”]=34.5;
map<string,float >::iterator it = m.begin();
cout<<it->first<<” ”<<it->second;
7. Multimap允许键值重复的元素插入
8. deque是双端队列, push_back在队尾插入元素,push_front在队头插入元素
9. bitset每一个元素只能是0或1
10. stack先进后出,后进先出
11. queue先进先出
12. priority_queue优先级队列也是先进行出,但是保证队首总是最大元素,因此出队时是从大到小