快排
sort(first, last ,compare) //[first, last)
//int类型
int arr[] = {3, 2, 5, 1, 4}
sort(arr, arr+5);
sort(arr, arr+5, greater<int>()); //后三个为降序
sort(arr, arr+5, cmp); // bool cmp(int a,int b){return a>b;}
sort(arr, arr+5, [](int a,int b){return a>b}) //第三项为lambda函数
//结构体类型
struct jgt{
string s,m,x,h;
int id;
}a[1000005];
bool cmp(jgt f1,jgt f2)
{
if(f1.s.length()!=f2.s.length())
return f1.s.length()<f2.s.length();
else if(f1.s!=f2.s) //短的在前,同样长度按照字典序小的在前,同用户
return f1.s<f2.s; //名先输入的在前面
else
return f1.id<f2.id;
}
stable_sort(a+1,a+n+1,cmp);
[first, last)范围内的值必须是一开始排好序的
移除[first, last)内连续重复项
去重之后返回最后一个元素的下一个地址
int a[]={3,2,2,1,2};
sort(a,a+5);
int n=unique(a,a+5)-a; //n是去重后的元素个数
cout<<n;
first: 查找起始位置(指针或 iterator)
last: 查找终止位置(指针或 iterator)
value: 查找的值
lower_bound() 查找的范围[first, last),返回的是序列中第一个小于等于value的位置,时间为O(log n)
[first, last)范围内的序列必须是提前排好序的,不然会错
如果序列内所有元素都比value小,则返回last
upper_bound()与lower_bound()相似,不同在于它返回序列中第一个大于value的位置
int a[]={1,3,2,4,5};
sort(a,a+5);
cout<<*upper_bound(a,a+5,3); //返回3
cout<<*lower_bound(a,a+5,3); //返回4
cout<<upper_bound(a,a+5,3)-a: //返回第一个大于3的数的下标
next_permutation(first, last),从小到大排列,用前先sort排序
用于求序列[first, last)元素全排列中当前排序的下一个排序
若下一个全排列存在,则返回1,否则返回0
//对int类型
int a[]={1,3,2};
sort(a,a+3);
do{
for(int i=0;i<3;i++)
cout<<a[i]<<" ";
cout<<endl;
}while(next_permutation(a,a+3));
//对string类型
string s;
while(cin>>s && s!="#") //对字符串s的全排列
{
sort(s.begin(),s.end());
cout<<s<<endl;
while(next_permutation(s.begin(),s.end()))
cout<<s<<endl;
}
//char类型
char s[205];
cin>>s; //遇到空格和回车键终止,自动在后面添加\0,所以strlen(s)表示的不是205,是字符'\0'及之前的字符一共的长度
sort(s,s+strlen(s));
do{
cout<<s<<endl;
}while(next_permutation(s,s+strlen(s)));
set中所有元素都是有序的,且只能出现一次,因为set中元素是有序的,所以储存的元素必须已经定义
与set类似的还有
multiset元素有序可以出现多次
unordered_set元素无序只能出现一次
unordered_multiset元素无序可以出现多次
//HDU1412 http://acm.hdu.edu.cn/showproblem.php?pid=1412
#include<iostream>
#include<set>
using namespace std;
int main()
{
set<int>s; //集合建立
int n,m,a;
while(cin>>n>>m)
{
s.clear(); //清空集合
for(int i=0;i<n+m;i++)
{
cin>>a;
s.insert(a); //向集合中插入元素
}
set<int>::iterator it; //建立set的迭代器
for(it=s.begin();it!=s.end();it++)
{
if(it==s.begin())
cout<<*it;
else
cout<<" "<<*it;
}
puts("");
}
return 0;
}