7

Why the output is coming to be 50 it should have been 20.

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
  int v[] = {10, 20, 30, 50, 20, 70, 30};

  int* i1;
  i1 = std::min_element(v + 3, v + 4);

  cout << *i1 << "\n";
  return 0;
}
0

1 Answer 1

15

STL algorithms operate on half-open ranges, which are usually denoted as [first, last). This means the first element is included in the range, the last element is not included. Hence

[v + 3, v + 4)

specifies a range of length 1, and the only element in that range has the value 50.The result of *std::min_element(v + 3, v + 4) can be nothing but 50.

Sign up to request clarification or add additional context in comments.

1 Comment

If you want to search the whole array, use std::min_element(v, v + 7) instead, or better std::min_element(std::begin(v), std::end(v))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.