简体   繁体   English

如何在不使用if语句的情况下找到数组中的最大值和最小值?

[英]How to find the maximum and minimum value in an array without using if statement?

How to find the maximum and minimum value in an array without using if statement.Are there any built in function in to do so in c++? 如何在不使用if语句的情况下在数组中找到最大值和最小值?在c ++中是否有内置函数可以这样做? If not is insertion sort the only way?Thanks in advance. 如果不是,插入排序是唯一的方法吗?谢谢。

Use std::minmax_element if you use C++11, or std::min_element / std::max_element if no. 如果使用C ++ 11,请使用std::minmax_element如果没有,请使用std::min_element / std::max_element

std::vector<int> v = {1,2,3,4};
auto minmax = std::minmax_element(v.begin(), v.end());
// now minmax.first points on 1 and minmax.second points on 4

However, if if condition should not be used internally - you can use following thing 但是,如果不应在内部使用该if condition -您可以使用以下内容

template<typename Iterator>
std::pair<Iterator, Iterator> minmax_element(Iterator first, Iterator last)
{
   Iterator min = first, max = first;
   while (first != last)
   {
      min = *min > *first ? first : min;
      max = *max > *first ? max : first;
      ++first;
   }
   return std::make_pair(min, max);
}

First of all, you can implement function sort(a, b), which returns pair of sorted values. 首先,您可以实现函数sort(a,b),该函数返回一对已排序的值。 To do it you can use following idea: min(a, b) = (a+b)/2 - |ab|/2 and max(a, b) = (a+b)/2 + |ab|/2 . 为此,您可以使用以下想法: min(a, b) = (a+b)/2 - |ab|/2max(a, b) = (a+b)/2 + |ab|/2

But here you have function |x|=abs(x), which uses 'if' inside. 但是这里有| x | = abs(x)函数,它在内部使用'if'。 So, we should implement 'abs' without any 'if'. 因此,我们应该实现没有任何“ if”的“ abs”。 One of the simpliest ways is following: abs(x) = sqrt(x*x) (it is very slow, but it is only an idea). 最简单的方法之一是: abs(x) = sqrt(x*x) (这很慢,但这只是一个想法)。 For integer values you can use these approaches: 1 , 2 , etc. 对于整数值,您可以使用这些方法: 12 ,等等。

So, you can implement function sort(a,b) which sorts only pair of values without any 'if'. 因此,您可以实现函数sort(a,b),该函数仅对一对值排序,而没有任何“ if”。 After it you can use this function to sort the array. 之后,您可以使用此功能对数组进行排序。 After it first element of that sorted array will be minimum value and last element will be maximum element. 在它之后,该排序数组的第一个元素将是最小值,最后一个元素将是最大元素。

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

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