简体   繁体   English

在 C++ 中比较两个整数的最有效和最干净的方法是什么?

[英]What is the most efficient and the clean way to compare two integers in C++?

Two variables两个变量

int x, y;

are going to be compared and the greater of them is going to be assigned to another variable,将进行比较,其中较大的将分配给另一个变量,

int greatest;

The first thing that comes to mind is首先想到的是

if (x > y) { greatest = x; }
else { greatest = y; }

Is there any other way that is much more efficient and clever ?有没有其他更有效和聪明的方法

The standard header <algorithm> provides the standard function std::max .标准头文件<algorithm>提供了标准函数std::max One of the overloads for this function compares two objects and returns a reference to the largest of the two.此函数的重载之一比较两个对象并返回对两个对象中最大的一个的引用。 In your case, the expression would be :在您的情况下,表达式将是:

auto greatest = std::max(x, y)

If there is a "most efficient" way to get the largest of the two you, you should rely on the underlying implementation to use it for you.如果有一种“最有效”的方法来获得两者中最大的一个,那么您应该依靠底层实现来为您使用它。 std::max should implement the best way of doing it. std::max应该实现最好的方法。 But even if you are using a weak standard library implementation that doesn't, the compiler should still catch this and optimize it.但即使您使用的不是弱标准库实现,编译器仍应捕获它并对其进行优化。

Remember that in c++ your code describes a behavior.请记住,在 C++ 中,您的代码描述了一种行为。 It is not a list of instructions that the compiler will execute verbatim.它不是编译器将逐字执行的指令列表。 Your code will be transformed by the compiler to implement these micro optimizations for you where they are known to exist.您的代码将由编译器转换,以在已知存在的地方为您实现这些微优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM