摘要:C++ algorithm
库中的sort
函数可以通过数组的初始地址和结束地址对数组元素进行自定义排序。
1.函数导入
在cpp文件中,头部写入#include<algorithm>
以包含algorithm
库
2.参数说明
函数声明:
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
first
:数组的起始地址。last
:数组结束地址。(数组中最后一个元素的下一个地址)comp
:自定义排序函数,默认升序。
自定义排序函数的声明形式:
bool comp(type x, type y);
返回值为true
时,说明元素x
与 元素y
的排序满足自定义排序规则。
返回值为false
时,说明元素x
与 元素y
的排序不满足自定义排序规则。
3.应用实例
- int数组排序
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int nums[] = { 3,2,1,3 };
sort(nums, nums+4);
// nums:数组起始地址(数组名指向数组的首元素)
// nums + 4 :数组结束地址(起始地址偏移4个int类型位长)
for (int num : nums) {
cout << num << ' ' ;
}
cout << endl;
}
输出结果:
1 2 3 3
- vector<int>数组排序
#include<iostream>
#include<algorithm>
#include<vector> // 使用vector时,要包含其头文件
using namespace std;
int main() {
vector<int> nums = { 3,2,1,3 };
sort(nums.begin(), nums.end());
// .begin():获取数组起始地址
// .end() :获取数组结束地址
for (int num : nums) {
cout << num << ' ' ;
}
cout << endl;
}
输出结果:
1 2 3 3
- vector<int>数组自定义排序
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
bool comp(int a, int b) { // 自定义降序
return a > b;
}
int main() {
vector<int> nums = { 3,2,1,3 };
sort(nums.begin(), nums.end(), comp);
for (int num : nums) {
cout << num << ' ';
}
cout << endl;
}
输出结果:
3 3 2 1
2021.10.8 第一次编辑