1
#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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
arnabanimesh
  • 275
  • 3
  • 11
  • 2
    You're passing in a range containing a single element, `3`. What did you expect the output to be? – Praetorian Feb 16 '16 at 04:59
  • The range should include 2 elements, a[1] & a[2]. If both the first and last element would be the same, then the range would have contained one element. So am I thinking in the wrong way? – arnabanimesh Feb 16 '16 at 05:23
  • Read [this](http://stackoverflow.com/q/9963401/241631). The standard library uses half open ranges, so the end iterator points to one past the last element. – Praetorian Feb 16 '16 at 05:59
  • If you run a loop sequentially over a vector (take the array in the question as a vector) and operate on each element up to last element i.e. a[4], then we need to run the loop up to &a[5] as the end element, which will result in vector subscript out of range. – arnabanimesh Feb 16 '16 at 08:18

1 Answers1

4

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335