如何按降序对标准数组进行排序 - C++ 11.
How to sort a standard array in descending order - C++ 11
有一些资源可以按降序对数组进行排序:
https://www.includehelp.com/stl/sort-an-array-in-descending-order-using-sort-function.aspx
如何在ASC和DESC模式下对数组进行排序C++?
https://www.geeksforgeeks.org/sort-c-stl/
但是没有一个解决为std::array
而不是基int myArr[]
类型执行此操作的问题。
我有这样的代码:
#include <iostream>
#include <array>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
int main(){
array<int, 5> myArray = {30, 22, 100, 6, 0};
for(int item : myArray){
cout << item << endl;
}
sort(myArray.begin(), myArray.end());
cout << "NOW, SORTED: " << endl;
for (int otheritem: myArray){
cout << otheritem << endl;
}
}
它产生:
30
22
100
6
0
NOW, SORTED:
0
6
22
30
100
但是,我正在尝试生成此输出:
100
30
22
6
0
通过按降序对数组进行排序。我已经尝试遵循上面SO帖子中的提示:
sort(myArray, myArray.size()+n, greater<int>());
但这会产生错误:
no instance of overloaded function "sort" matches the argument list -- argument types are: (std::array<int, 5ULL>, unsigned long long, std::greater<int>)
如何按降序对int
standard array
进行排序?
与原始数组不同,std::array
不会隐式转换为指针(即使你可以从std::array::data
中显式获取指针(,你应该使用begin()
和end()
,它们通常用于从 STL 容器中获取迭代器。
sort(myArray.begin(), myArray.end(), greater<int>());
或
sort(std::begin(myArray), std::end(myArray), greater<int>());
PS:后者也适用于原始数组。
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 下面是排序算法O(n)吗
- std::sort()函数无法对向量的一部分进行排序
- shell排序中的交换和比较
- clang格式:禁用排序包含
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 试图在c++中对数字列表进行排序
- 如何在C++中对数组进行冒泡排序