【发布时间】:2020-11-19 07:23:51
【问题描述】:
我目前遇到一个 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::sort。 -
我总是对
fastest这个形容词很感兴趣。像这样使用与速度无关。这意味着使用最少的代码,或者没有任何我目前不理解的东西。对于新手来说,一切都很好,但我想知道为什么最快,为什么不说最简单或最简单。 -
具有讽刺意味的是,列出所有可能的组合可能是对五个数字进行排序的最快方法,而最快确实意味着比任何其他方法花费的 CPU 时间更少。