arnabanimesh
arnabanimesh

Reputation: 277

Unexpected max_element behaviour

#include<iostream>
#include<algorithm>

int main()
{
    int a[3]={5,3,4};
    std::cout<<*std::max_element(&a[1],&a[2])<<"\n";
    return 0;
}

This code is displaying 3 as output.

Upvotes: 1

Views: 90

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

You should write

std::cout << *std::max_element( a, a + 3 ) << "\n";

Or include header <iterator> and write

#include <iterator>

//...
std::cout << *std::max_element( std::begin( a ), std::end( a ) ) << "\n";

The range for the algorithm is specified like [first, last ) where the element pointed to by the iterator last is not included in the range.

So for these arguments of the algorithm [&a[1],&a[2] ) element a[2] will not take part in the comparisons with other elements of the array. This range specifies only one element a[1] of the array.

Take into acount that indices for arrays start with 0.

Upvotes: 3

Related Questions