Most efficient way to find the greatest of three ints

前端 未结 14 1292
离开以前
离开以前 2020-12-30 07:58

Below is my pseudo code.

function highest(i, j, k)
{
  if(i > j && i > k)
  {
    return i;
  }
  else         


        
14条回答
  •  别那么骄傲
    2020-12-30 08:50

    The easiest way to find a maximum or minimum of 2 or more numbers in c++ is:-

    int a = 3, b = 4, c = 5;
    int maximum = max({a, b, c});
    
    int a = 3, b = 4, c = 5;
    int minimum = min({a, b, c});
    

    You can give as many variables as you want.

    Interestingly enough it is also incredibly efficient, at least as efficient as Ignacio Vazquez-Abrams'solution (https://godbolt.org/z/j1KM97):

            mov     eax, dword ptr [rsp + 8]
            mov     ecx, dword ptr [rsp + 4]
            cmp     eax, ecx
            cmovl   eax, ecx
            mov     ecx, dword ptr [rsp]
            cmp     eax, ecx
            cmovl   eax, ecx
    

    Similar with GCC, while MSVC makes a mess with a loop.

提交回复
热议问题