cpp vector从大到小排序
时间: 2023-07-25 10:39:54 浏览: 113
你可以使用 `sort` 函数和一个自定义的比较函数来实现从大到小排序:
```cpp
#include <algorithm>
#include <vector>
bool cmp(int a, int b) {
return a > b; // 从大到小排序
}
int main() {
std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
std::sort(v.begin(), v.end(), cmp);
// 输出排序后的结果
for (auto x : v) {
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
```
输出结果为:
```
9 6 5 5 5 4 3 3 2 1 1
```
相关问题
vector按大到小排列
向量(vector)在某些编程语言中,比如C++中的标准模板库(STL),默认是按照元素值的顺序存储的,即升序排列。如果你想让vector中的元素按从大到小的顺序排列,你可以采用以下几种方法:
1. **使用`std::sort`函数**:可以使用`std::sort`函数,并提供自定义比较函数来实现降序排序。例如,对于数值类型的vector,可以传入一个比较函数,使得较大的元素排在前面。
```cpp
#include <algorithm>
bool compare(const std::pair<int, int>& a, const std::pair<int, int>& b) {
return a.second > b.second;
}
// 然后对vector调用:
std::sort(vector.begin(), vector.end(), compare);
```
2. **使用`std::stable_sort`函数**:如果需要保持原元素相对位置不变,可以选择`std::stable_sort`,并同样提供比较函数。
3. **使用`std::partial_sort`**:如果只需要部分元素按降序排列,可以使用`std::partial_sort`。
4. **自定义容器**:如果你有特定需求,还可以创建一个自定义容器,比如使用优先队列`std::priority_queue`,它本身就是按大到小的顺序存放元素的。
注意,上述操作会改变vector本身的原始顺序。如果你不想改变原有的数据结构,可以先复制一份vector再进行排序。
cpp 使用sort从大到小排序
可以使用sort函数的第三个参数来指定排序规则,例如:
```cpp
#include <algorithm>
#include <vector>
using namespace std;
bool cmp(int a, int b) {
return a > b;
}
int main() {
vector<int> nums = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
sort(nums.begin(), nums.end(), cmp); // 使用自定义的比较函数
for (int num : nums) {
printf("%d ", num);
}
return 0;
}
```
输出结果为:9 6 5 5 5 4 3 3 2 1 1
阅读全文
相关推荐














