gpt4 book ai didi

c++ - 如何在没有 if 语句的情况下从最小到最大对一组整数进行排序?

转载 作者:行者123 更新时间:2023-12-01 14:34:01 25 4
gpt4 key购买 nike

我目前遇到一个 C++ 问题,该问题要求我将五个输入的整数从小到大排序。我试过使用 if 语句来执行此操作,但列出所有可能的组合似乎效率太低。我也尝试过 min 和 max 函数,但它们只适用于最小和最大的两个整数。对它们进行排序的最快方法是什么?

#include <iostream>
using namespace std;

int main() {

cout << "Enter five integers. \n\n>";
int a, b, c, d, e;
cin >> a >> b >> c >> d >> e;

int first = min({a, b, c, d, e});
int fifth = max({a, b, c, d, e});

cout << first << fifth << "\n"; //This is where I want to output the middle three integers in order

cout << "\n";
return 0;
}

到目前为止,这是我的代码。 ^

最佳答案

标准库有一个函数叫std::sort ,适用于任何范围。您可以将数字放在一个数组中,也可以将它们放在其他一些容器中(例如 std::vector)。在这种情况下,考虑到五项限制,数组就足够简单了。例如:

#include <iostream>
#include <algorithm>
#include <array>
#include <iterator>

int main() {
std::array<int, 5> numbers;

std::cout << "Enter five integers. \n\n>";

// Read numbers into array.
for (auto & i : numbers) {
std::cin >> i;
}

// Sort the entire array.
std::sort(std::begin(numbers), std::end(numbers));

// Display sorted numbers.
for (auto i : numbers) {
std::cout << i << '\n';
}

return 0;
}

关于c++ - 如何在没有 if 语句的情况下从最小到最大对一组整数进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63158083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com