C ++ finds the (largest) index of the largest element in an array

I have an array of values ​​and a method to find the index of the largest element in the array.

value = distance(arrayOfValues, max_element(arrayOfValues, arrayOfValues + N));

However, if there are several instances of the highest value, for example. {3,1,3,4,4,3,2} it only returns the smallest index (in this case 3), while I would like it to return the largest index, in this case 4.

The only way I can do this is to create a new array identical to "arrayOfValues", but vice versa, and then apply the above method.

Is there an easier way to do this to avoid creating a new array? Perhaps manipulating the above code snippet?

+1
source share
4

for if. - ...

int indexToReturn = 0;
int indexValue = 0;
int newValue = 0;
for (int i = 0; i < arrayCount; i++) {
    newValue = arrayOfValues[i];
    if (newValue >= indexValue) {
        indexToReturn = i;
        indexValue = newValue;
    }
// At the end of this loop the value you want is indexToReturn
}
+2

, :

const int index =
    std::distance(std::begin(arrayOfValues),
        std::max_element(std::begin(arrayOfValues), std::end(arrayOfValues),
        [](const int& lhs, const int& rhs) {
            return std::make_tuple(lhs, &lhs)
            < std::make_tuple(rhs, &rhs);
        }
        ));

+3

Use reverse iterators in your range.

You pass endin the reverse iterator constructor to start the opposite, and start the reverse end.

template<class It>
std::reverse_iterator<It> rit(It i){return {i};}

template<class C>
struct backwards_t {
  C c;
  auto end() {
    using std::begin;
    return rit(begin(c));
  }
  auto begin() {
    using std::end;
    return rit(end(c));
  }
};
template<class C>
backwards_t<C> backwards(C&&c){return {std::forward<C>(c)};}

is a C ++ 14 way.

auto yarra = backwards(array);
auto it = std::max_element(yarra.begin(), yarra.end());

it also allows you to call backwardsin a loop for(:)and iterate backward.

+3
source

You probably have something like this:

int maxIdx = 0;  
for(int i = 0; i < n; ++i)
  if(a[maxIdx] > a[i])
    maxIdx = i;

return maxIdx;

You just need to add one character to the if statement:

if(a[maxIdx] >= a[i])
  maxIdx = i;
+2
source

Source: https://habr.com/ru/post/1569977/


All Articles