- 1、默认排序
默认是升序排序less<typeName>()
,也可以使用降序排序greater<typeName>()
//实例1
vector<int> vec{2, 1, 3, 4, 6, 5};
sort(vec.begin(), vec.end());
for (int v : vec) {
cout << v << " ";
}
cout << endl;
/*
输出为
1 2 3 4 5 6
*/
//实例2
vector<int> vec{2, 1, 3, 4, 6, 5};
sort(vec.begin(), vec.end(), greater<int>());
for (int v : vec) {
cout << v << " ";
}
cout << endl;
/*
输出为
6 5 4 3 2 1
*/
-
2、使用自定义的比较函数
-
直接定义比较函数;
//实例1
bool cmp(const int& a, const int& b) {
return a < b;
}
vector<int> vec{2, 1, 3, 4, 6, 5};
sort(vec.begin(), vec.end(), cmp);
for (int v : vec) {
cout << v << " ";
}
cout << endl;
/*
输出为
1 2 3 4 5 6
*/
//实例2
bool cmp(const int& a, const int& b) {
return a > b;
}
vector<int> vec{2, 1, 3, 4, 6, 5};
sort(vec.begin(), vec.end(), cmp);
for (int v : vec) {
cout << v << " ";
}
cout << endl;
/*
输出为
6 5 4 3 2 1
*/
- 进行函数重载;
//实例1
struct cmp {
bool operator() (const int& a, const int& b) {
return a < b;
}
};
vector<int> vec{2, 1, 3, 4, 6, 5};
sort(vec.begin(), vec.end(), cmp());
for (int v : vec) {
cout << v << " ";
}
/*
输出为
1 2 3 4 5 6
*/
//实例2
struct cmp {
bool operator() (const int& a, const int& b) {
return a > b;
}
};
vector<int> vec{2, 1, 3, 4, 6, 5};
sort(vec.begin(), vec.end(), cmp());
for (int v : vec) {
cout << v << " ";
}
/*
输出为
6 5 4 3 2 1
*/