1.reverse和unique
#include<algorithm> #include<iostream> #include<vector> using namespace std; int main() { vector<int> v({1,2,3,4,5,5}); reverse(v.begin(),v.end());//O(n) for(auto x:v) cout<<x<<" "; cout<<endl; int a[]={1,2,2,3,3}; //unique会对相同元素在一起的去重 int m=unique(a,a+5)-a;cout<<m<<endl; //m为地址间的差值 for(int i=0;i<m;++i) cout<<a[i]<<" "; cout<<endl; m=unique(v.begin(),v.end())-v.begin();cout<<m<<endl; v.erase(unique(v.begin(),v.end()),v.end()); for(auto x:v) cout<<x<<" "; }
2.random_shuffle
#include<algorithm> #include<iostream> #include<vector> #include<ctime> using namespace std; int main() { srand(time(0)); int a[]={1,2,3,4,5}; random_shuffle(a,a+5); for(auto x:a) cout<<x<<" "; }
3.sort
#include<algorithm> #include<iostream> #include<vector> #include<ctime> struct st{ int a,b; //重载运算可以看作当前结构体是否排在x前面 bool operator < (const st x) const{ return a>x.a; } }s[2]; bool cmp(int a,int b)//cmp可以看作a是否应该排在b的前面 { return (a%2)&&!(b%2); } using namespace std; int main() { s[0]={1,2}; s[1]={2,1}; sort(s,s+2); cout<<s[0].a<<" "<<s[0].b<<endl; int p[]={1,2,3,4,5}; sort(p,p+5,cmp);//cmp实现了将奇数排在偶数前 for(auto x:p) cout<<x<<" "; }
4.upper_bound和lower_bound
#include<iostream> #include<algorithm> using namespace std; int main() { int a[]={1,2,4,5}; int *p=lower_bound(a,a+4,2); int *q=upper_bound(a,a+4,2); cout<<*p<<" "<<*q<<endl; int m=p-a,n=q-a; cout<<m<<" "<<n<<endl;//得到下标 cout<<q-p<<endl;//得到2出现的次数 }标签:常用,main,cout,int,namespace,bound,include,库函数 From: https://www.cnblogs.com/ruoye123456/p/17036704.html