首先 常用库函数基本都在头文件algorithm里面
但是 有些比赛是禁止使用这个头文件的 因为里面的函数 实在是太强了
algorithm翻译成中文是什么意思 就是算法啊 整一个头文件就是算法库函数啊
1.reverse 翻转(非常非常非常重要)
翻转一个 vector:
reverse(a.begin(),a.end());
翻转一个数组,元素存放在下标1~n:
reverse(a+1,a+1+n);
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int>a({1,2,3,4,5});//c++11写法
reverse(a.begin(),a.end());
for(int x:a)cout<<x<<' '<<endl;
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int a[]={1,2,3,4,5};
// reverse(a.begin(),a.end());
reverse(a,a+5);//取数组最后一个元素的下一位 左闭右开
for(int x:a)cout<<x<<' '<<endl;
return 0;
}
2.unique 去重(得保证相同元素挨在一起)
返回去重之后的尾迭代器(或指针),仍然为前闭后开,即这个迭代器是去重之后,末尾元素的下一个位置。该函数常用于离散化,利用迭代器(或指针)的减法,可计算出去重后的元素个数
把一个vector去重
int m=unique(a.begin(),a.end())-a.begin();
数组中不同元素的数量 得减去迭代器 也就是新数组的begin
原理是把不重复的元素放到新数组的开头
把一个数组去重,元素存放在小标1~n:
int m=unique(a+1,a+1+n)-(a+1)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int a[]={1,1,2,2,3,3,4};
// reverse(a.begin(),a.end());
// reverse(a,a+5);//取数组最后一个元素的下一位 左闭右开
int m=unique(a,a+7)-a;
cout<<m<<endl;
for(int i=0;i<m;i++)cout<<a[i]<<endl;
//for(int x:a)cout<<x<<' '<<endl;
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int>a({1,1,2,2,3,3,4});
a.erase(unique(a.begin(),a.end()),a.end());
for(int x:a)cout<<x<<' '<<endl;
return 0;
}
3.random_shuffle 随机打乱
一般用的不多 一般是自己生成数据的时候用
用法同reverse
4.sort(非常非常非常重要又好用)
对两个迭代器(或指针)指定的部分进行排序。可以在第三个参数传入定义大小比较的函数或者重载“小于号”运算符
把一个int数组(元素存放在下标1~n)从大到小排序,传入比较函数:
int a[MAX_SIZE]
bool cmp(int a,int b){return a>b}
sort(a+1,a+1+n,cmp);
把自定义的结构体vector排序,重载“小于号”运算符
// 数组从小到大排序
sort (a.begin(),a.end());
如果想从大到小排序 加上greater<int>()
// 数组从大到小排序
sort (a.begin(),a.end(),greater<int>());
当然你也可以自定义排序
bool cmp(int a,int b )//a是否排在b的前面
{
return a<b;
}
int main()
{
int a[]={1,4,3,5,4,6,5};
sort (a.begin(),a.end(),cmp);
return 0;
}
也可以把自定义的结构体vector排序,重载“小于号”运算符
struct Rec
{
int x,y;
bool operator<(const Rec &t)const
{
return x<t.x;
}
}a[5];
5.lower_bound/upper_bound 二分
lower_bound的第三个参数传入一个元素x,在两个迭代器(指针)指定的部分上执行二分查找,返回第一个大于等于x的元素的位置的迭代器(指针)。
upper_bound的用法和lower_bound大致相同,唯一的区别是查找第一个大于x的元素。当然,两个迭代器(指针)指定的部分应该是提前排行序的。
在有序int数组(元素存放在下标1~n)中查找大于等于x的最小的整数的下标:
int l = lower_bound(a+1,a+1+n,x)-a;
在有序vector<int>中查找小于等于的最大整数(假设存在):
int y=*--upper_bound(a.begin(),a.end(),x)
输出值如下
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[] = {1, 2, 4, 5, 6};
int *p = lower_bound(a, a + 5, 3);
cout << *p << endl;//返回第一个大于等于的数 4
return 0;
}
输出对应下标如下
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[] = {1, 2, 4, 5, 6};
int t = lower_bound(a, a + 5, 3) - a;
cout << t << endl;//返回第一个大于等于的数的下标
return 0;
}