1.merge的用法
用于将两个有序的容器合并到另外一个容器,合并后的容器也是有序的。头文件#include <algorithm>
#include <iostream>
#include <vector>
#include <algorithm>
int main(){
std::vector<int> vec0;
std::vector<int> vec1;
std::vector<int> vec2;
vec0.push_back(5);
vec0.push_back(7);
vec0.push_back(9);
vec1.push_back(4);
vec1.push_back(6);
vec1.push_back(8);
vec2.resize(vec0.size()+vec1.size());
std::merge(vec0.begin(),vec0.end(),vec1.begin(),vec1.end(),vec2.begin());
std::for_each(vec2.begin(),vec2.end(),[](int i){std::cout<<i<<std::endl;});//打印结果是4,5,6,7,8,9
return 0;
}
2.sort的用法
sort用于对容器中的元素进行排序,#include <algorithm>
(1)默认是升序排序
std::vector<int> vec3;
vec3.push_back(3);
vec3.push_back(2);
vec3.push_back(1);
std::sort(vec3.begin(),vec3.end());
std::for_each(vec3.begin(),vec3.end(),[](int i){std::cout<<i<<std::endl;});
(2)可以传入一个回调函数改变默认的排序规则
std::vector<int> vec4;
vec4.push_back(1);
vec4.push_back(2);
vec4.push_back(3);
std::sort(vec4.begin(),vec4.end(),[](int val,int val1){return val>val1;});
std::for_each(vec4.begin(),vec4.end(),[](int i){std::cout<<i<<std::endl;});
3.random_shuffle的用法
random_shuffle用于对容器内的元素打乱顺序随机排列,类似洗牌。#include <algorithm>
std::vector<int> vec5;
vec5.push_back(1);
vec5.push_back(2);
vec5.push_back(3);
vec5.push_back(4);
vec5.push_back(5);
std::random_shuffle(vec5.begin(),vec5.end());
std::for_each(vec5.begin(),vec5.end(),[](int i){std::cout<<i<<std::endl;});
4.reverse的用法
reverse用于反转容器中的元素,即最后一个变为第一个,倒数第二个变为正数第二个...#include <algorithm>
std::vector<int> vec6;
vec6.push_back(1);
vec6.push_back(2);
vec6.push_back(3);
vec6.push_back(4);
vec6.push_back(5);
std::reverse(vec6.begin(),vec6.end());
std::for_each(vec6.begin(),vec6.end(),[](int i){std::cout<<i<<std::endl;});