有没有更好的方法对C++中的三个整数进行排序?

Is there any better way to sort three integers in C++?

本文关键字:整数 三个 排序 方法 更好 C++ 有没有      更新时间:2023-10-16

在我正在使用的编程教科书(Bjarne Stroustrup的编程:使用C++的原则和实践(中,我正在尝试做一个在早期章节中找到的练习(在引入数组或其他任何东西之前(,但我只能使用一种对我来说看起来很奇怪和"倒退"的算法来解决它。练习是从控制台读取 3 个整数,并根据大小对它们进行排序,用逗号分隔。这是我写的:

#include <iostream>
using namespace std;
int main()
{
int a, b, c;
cout << "Enter three integers: ";
cin >> a >> b >> c;
if (a <= b and a <= c) {
cout << a << ", ";
if (b < c)
cout << b << ", " << c;
else
cout << c << ", " << b;
return 0;
}
if (b <= a and b <= c) {
cout << b << ", ";
if (a < c)
cout << a << ", " << c;
else
cout << c << ", " << a;
return 0;
}
if (c <= a and c <= b) {
cout << c << ", ";
if (a < b)
cout << a << ", " << b;
else
cout << b << ", " << a;
return 0;
}
return 0;
}

我知道它很长,但我想不出任何其他方法可以使用我可以使用的工具(if 语句(来做到这一点。你能帮我看看是否有其他方法可以做到吗?谢谢!

取决于你所说的"更好"是什么意思。有一种更短的方法可以做到这一点,就像C++中的大多数其他事情一样:

#include <iostream>
#include <iterator>
#include <algorithm>
#include <cstdio>
int main() {
std::istream_iterator<int> it{std::cin};
int a[]{ *it++, *it++, *it++ };
std::sort(std::begin(a), std::end(a));
std::printf("%d, %d, %dn", a[0], a[1], a[2]);
}

是否越短越好是另一个讨论。

您也可以在不调用std::sort的情况下执行此操作,手动排序:

// Put the smallest number in a.
if (b < a)
std::swap(a, b);
if (c < a)
std::swap(a, c);
// Arrange the other two numbers.
if (c < b)
std::swap(b, c);
std::cout << a << ", " << b << ", " << c << 'n';

希望这有帮助:

#include <iostream>
using namespace std;
int main()
{
int a, b, c, x, mid, max;
cout << "Enter three integers: ";
cin >> a >> b >> c;
if (a<b){
x = a;
max = b;
}
else {
x = b;
max = a;
}
if (c < x){
mid = x;
x = c;
}
if (c > max){
mid = max;
max = c;
}
else
mid = c;
cout << x << ", " << mid <<", "<<max;
}