C++中algorithm头文件中一些函数使用记录
原创
©著作权归作者所有:来自51CTO博客作者mb5dbc2345bf8de的原创作品,请联系作者获取转载授权,否则将追究法律责任
文章目录
- 1.1 基本数据类型排序
- 1.2 结构体向量排序
- 2、reverse
- 3、find
- 4、count
- 5、count_if
- 6、lower_bound,upper_bound
- 7、max_element,min_element
- 8、next_permutaion
1、sort()
vetor<int> vec;
sort(vec.begin(),vec.end(),way);
1.1 基本数据类型排序
默认情况下way是less <ElemType >(),从小到大排序,若改成greater<ElemType>()则是从大到小排序。
1.2 结构体向量排序
此时sort函数的way需要自定义。
struct Book{
int price;
string name;
}
bool cmy(Book a , Book b){
return a.price > b. price;
}
sort(vec.begin(),vec.end(),cmy);
使得原向量按照price从大到小排序。大于号表示从大到小,小于号表示从小到大
与优先队列中优先级设置过程正好相反。
2、reverse
能够使得容器元素逆置。
string st = "abcdefg";
reverse(st.begin(),st.end());
cout << st;
3、find
find函数能够寻找vector向量中指定元素的地址,减去vector.begin()能够得到指定元素下标。如果找不到,就返回vector的end()
#include<set>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main(){
vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
vector<int>::iterator it = find(vec.begin(),vec.end(),3);
//返回元素3的下标
cout << it-vec.begin();
return 0;
}
4、count
vector<int> vec;
count(vec.begin(), vec.end(),2);
返回向量中等于2的元素个数
5、count_if
返回符合自定义条件的个数
bool IsDigit(char c){
return isdigit(c);
}
int cnt = count_if(s.begin(),s.end(),IsDigit);
6、lower_bound,upper_bound
vector<int> vec;
lower_bound(vec.begin(), vec.end(),num);
返回第一个大于等于num的位置,如果不存在则返回end
vector<int> vec;
upper_bound(vec.begin(), vec.end(),num);
返回第一个大于num的位置,如果不存在则返回end
vector<int> vec;
lower_bound(vec.begin(), vec.end(),num,greater<type>());
返回第一个小于等于num的位置,如果不存在则返回end
vector<int> vec;
upper_bound(vec.begin(), vec.end(),num,greater<type>());
返回第一个小于num的位置,如果不存在则返回end
7、max_element,min_element
int arr[9] = {1,3,5,8,1,55,6,2,1};
cout << *max_element(arr,arr+9) << endl;
cout << *min_element(arr,arr+9) << endl;
cout << max_element(arr,arr+9)-arr << endl;
cout << min_element(arr,arr+9)-arr << endl;
输出
8、next_permutaion
使用next_permutaion函数能够对升序的数组进行全排列
#include<bits/stdc++.h>
using namespace std;
int main()
{
int num[10]={0,1,2,3,4,5,6,7,8,9};
do
{
cout << num[1] << " " << num[2] << " " << num[3] << " " << num[4] << endl;
}while(next_permutation(num+1,num+5));
return 0;
}
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1