酷代码 AI
菜单
服务商

C++实现非负整数序列从大到小排序并输出

以下是实现该功能的 C++ 代码: ```cpp #include <iostream> #include <algorithm> #include <vector> int main() { int n; // 读取序列的个数 std::cin >> n; std::vector<int> a(n); // 读取 n 个非负整数 for (int i = 0; i < n; ++i) { std::cin >> a[i]; } // 对数组进行排序,从大到小 std::sort(a.begin(), a.end(), std::greater<int>()); // 输出排序后的数组 for (int i = 0; i < n; ++i) { if (i > 0) { std::cout << " "; } std::cout << a[i]; } std::cout << std::endl; return 0; } ``` ### 代码解释 1. **输入处理**:首先读取整数 `n`,表示序列的个数。然后使用 `std::vector` 存储 `n` 个非负整数。 2. **排序操作**:使用 `std::sort` 函数对数组进行排序,通过 `std::greater<int>()` 实现从大到小的排序。 3. **输出结果**:遍历排序后的数组,按要求输出,数与数之间用空格隔开。 ######[AI问答 | 341点数解答 | 2026-04-04 17:26:29]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]