云起工作室 15711107967
04-51cto-算法
2023-01-29 17:09:37

#include<algorithm>


文档地址

https://cplusplus.com/reference/algorithm


vector<int> v;


1、find

vector<int>:iterator it=find(v.begin(),v.end(),3) 从开始到结尾查找值为3 的迭代器


2、find_if

2.1、bool is3(int x){

return x==3;

}

vector<int>::iterator it = find_if(v.begin(),v.end(),is3) ;会将begin到end的元素一个一个传入方法is3里

2.2、struct is3(){

bool operator ()(int x){

return x==3;

}

}

vector<int>::iterator it = find_if( v.begin(),v.end(),is3() );

3、find_first_if(v.begin(),v.end(),v2.begin(),v2.end()))

4、for_each(v.begin(),v.end(),fun) 将每个元素一次作为参数传入到一元函数fun遍历

5、count(v.begin(),v.end(),2) 返回2出现的次数

6、count_if(v.begin(),v.end(),fun)

7、vector<int>::iterator it = search(v.begin(),v.end(),v2.begin(),v2.end())

8、search_n(v.begin(),v.end(),2,4) 查找连续的两个4


9、random_shuffle(v.begin(),v.end()) 打乱顺序

10、replace(v.begin(),v.end(),3,333) 将所有元素3 替换成333

11、replace_if(v.begin(),v.end(),fun,333) 一次传入fun 返回true的元素替换成333

12、replace_copy(v.begin(),v.end(),v2.begin(),3,333) 将所有元素copy到v2并将3替换成333

13、fill(v.begin(),v.end(),111) 将容器v每个元素设置为111

14、vector<int>::iterator it = remove(v.begin(),v.end(),3) 移除元素3,并将删除的元素的后边元素前移不改变容器大小 返回最后一个元素位置

15、reverse(v.begin(),v.end()) 反转元素顺序

16、unique(v.begin(),v.end()) 删除连续重复元

17、transform( v.begin(),v.end(),v2.begin(),fun) 经fun加工后的元素返回给v2


划分、排序

18、partition(v.begin(),v.end(),fun) 分区 将fun返回true 的放到前边,为false 的放到后边

19、stable_partition(v.begin(),v.end(),fun)

20、sort(v.begin(),v.end(),greater<int>()) 降序排列; 第三个参数可以不传,默认为less 升序

21、stable_sort(v.begin(),v.end(),greate<int>()) 有重复的元素会有作用

22、partial_sort(v.begin(),v.begin()+3,v.end(),greater<int>()) 将最大的前三个排序放到最前,其他忽略排序

23、nth_element(v.begin(),v.begin()+3,v.end()) 把第n大的元素拍到第n个位置,不关心其他元素