创建一个函数对象Descending,用于对整数进行降序排序。 使用 std:sort算法和Descending函数对象对一个vector容器中元素进行排序。输出排序后的数组。
在C++中,我们可以创建一个自定义的比较函数对象Descending
来实现整数的降序排序。这个函数对象通常是一个名为struct
或者class
的实例,它包含一个操作符>()
,该操作符返回两个整数是否应该按照降序排列。
首先,我们创建Descending
函数对象:
```cpp
#include
// 自定义的降序比较函数对象 struct Descending { bool operator()(int a, int b) const { return a > b; } };
void sortDescending(std::vector
int main() {
std::vector
声明一个整型数组,使用C++标准模板库STL中的查找算法find()进行数据的查找,然后应用排序算法Sort(),并配合使用标准函数对象Greater<T>对数据进行升序和降序排序。
在C++中,你可以声明一个std::array
(固定大小数组)或std::vector
(动态大小数组)来存储整数。这里以std::vector
为例,因为它更常用于此类操作:
#include <iostream>
#include <algorithm> // 包含sort和find等算法
#include <vector>
#include <functional> // 包含Greater<T>作为比较器
// 定义整型向量
std::vector<int> numbers = {9, 4, 6, 1, 8, 3};
// 使用find()查找指定元素
size_t index = std::find(numbers.begin(), numbers.end(), 8); // 查找8的位置
if (index != numbers.end()) {
std::cout << "Element found at index: " << index - numbers.begin() << "\n";
} else {
std::cout << "Element not found.\n";
}
// 使用Sort()进行升序排序
std::sort(numbers.begin(), numbers.end());
// 输出升序排序后的数组
std::cout << "Sorted in ascending order: ";
for (const auto& num : numbers) {
std::cout << num << " ";
}
std::cout << "\n";
// 使用 Greater<T> 进行降序排序
using CompareDesc = std::greater<int>; // 或者 std::greater_equal<int> 如果包括重复元素
std::sort(numbers.begin(), numbers.end(), CompareDesc());
// 输出降序排序后的数组
std::cout << "Sorted in descending order: ";
for (const auto& num : numbers) {
std::cout << num << " ";
}
std::cout << "\n";
用C++ 编写程序对10个整数进行排序。随机输入10个整数,然后进行排序,再输出从小到大的顺序和从大到小的顺序。
在C++中,你可以使用<algorithm>
库提供的排序算法如sort()
来实现这个功能。这里是一个简单的例子,使用冒泡排序算法和快速排序算法分别实现从大到小和从小到大的排序:
#include <iostream>
#include <vector>
#include <cstdlib> // 需要头文件用于获取随机数
#include <ctime> // 时间函数
// 冒泡排序从小到大
void bubbleSort(std::vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (nums[j] > nums[j + 1]) {
std::swap(nums[j], nums[j + 1]);
}
}
}
}
// 快速排序从大到小
void quickSort(std::vector<int>& nums, int low, int high) {
if (low < high) {
int pivot = nums[high]; // 最后一个元素作为基准
int i = low - 1;
for (int j = low; j < high; ++j) {
if (nums[j] >= pivot) {
i++;
std::swap(nums[i], nums[j]);
}
}
std::swap(nums[i + 1], nums[high]);
quickSort(nums, low, i);
quickSort(nums, i + 2, high);
}
}
int main() {
srand(time(0)); // 设置随机种子
std::vector<int> nums(10); // 创建一个包含10个整数的向量
// 随机生成10个整数并填充向量
for (auto& num : nums) {
num = rand() % 100; // 取0-99之间的随机整数
}
// 输出原始数组
std::cout << "Original array: ";
for (const auto& num : nums) {
std::cout << num << " ";
}
std::cout << "\n";
// 冒泡排序从小到大
bubbleSort(nums);
std::cout << "Sorted in ascending order: ";
for (const auto& num : nums) {
std::cout << num << " ";
}
std::cout << "\n";
// 快速排序从大到小
quickSort(nums, 0, nums.size() - 1);
std::cout << "Sorted in descending order: ";
for (const auto& num : nums) {
std::cout << num << " ";
}
std::cout << "\n";
return 0;
}
相关推荐
















