排序函数
sort()
排序函数
1. 使用lambda
表达式进行排序
cpp
vector<int> arr = {4,5,3,8,2,1,6,7};
sort(arr.begin(), arr.end(), [](int a, int b) {
return a > b;
});
for (int num : arr) {
cout << num << " "; //8 7 6 5 4 3 2 1
}
sort(arr.begin(), arr.end(), [](int a, int b) {
return a < b;
});
for (int num : arr) {
cout << num << " "; //1 2 3 4 5 6 7 8
}
2. 使用greater
和lesser
函数进行排序
cpp
vector<int> arr = {4,5,3,8,2,1,6,7};
sort(arr.begin(), arr.end(),greater<int>());
for (int num : arr) {
cout << num << " "; // 8 7 6 5 4 3 2 1
}
cout << endl;
sort(arr.begin(), arr.end(), less<int>());
for (int num : arr) {
cout << num << " "; // 1 2 3 4 5 6 7 8
}
3. 对结构体进行sort
排序
cpp
typedef struct node {
int x,y,z;
bool operator<(const node& other) const {
if(this->x==other.x){
if(this->y==other.y){
return this->z<other.z;
}
return this->y<other.y;
}
return this->x<other.x;
}
bool operator>(const node& other) const {
if(this->x==other.x){
if(this->y==other.y){
return this->z>other.z;
}
return this->y>other.y;
}
return this->x>other.x;
}
} node;
// 不添加greater和lesser函数,默认使用<进行排序
int main(){
vector<node> arr = {{1, 2, 3}, {1, 2, 4}, {1, 3, 5}, {2, 2, 6}, {2, 3, 7}, {3, 2, 8}};
sort(arr.begin(), arr.end(), greater<node>()); //使用重载的>进行排序
for (const node& n : arr) {
cout << "(" << n.x << " " << n.y << " " << n.z << ") ";
}
cout << endl;
sort(arr.begin(), arr.end(), less<node>()); //使用重载的<进行排序
for (const node& n : arr) {
cout << "(" << n.x << " " << n.y << " " << n.z << ") ";
}
return 0;
}
4. 对pair
进行sort
排序
cpp
vector<pair<int, int>> arr = {{1, 2}, {3, 1}, {2, 3}, {4, 0}};
sort(arr.begin(), arr.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
return a.first < b.first; // 按照第一个元素升序排序
});
for (const auto& p : arr) {
cout << "(" << p.first << ", " << p.second << ") "; // (1, 2) (2, 3) (3, 1) (4, 0)
}
5. 对tuple
进行sort
排序
cpp
vector<tuple<int, int, int>> arr = {{1, 2, 3}, {3, 1, 2}, {2, 3, 1}, {4, 0, 5}};
sort(arr.begin(), arr.end(), [](const tuple<int, int, int>& a, const tuple<int, int, int>& b) {
return get<0>(a) < get<0>(b); // 按照第一个元素升序排序
});
for (const auto& t : arr) {
cout << "(" << get<0>(t) << ", " << get<1>(t) << ", " << get<2>(t) << ") "; // (1, 2, 3) (2, 3, 1) (3, 1, 2) (4, 0, 5)
}