0

I expected the following program will give 0 as output but actually it is 1. Why the first element is considered and last element is not considered for min calculation?

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<int> arr = {5,4,3,2,1,0};
    cout<<*min_element(arr.begin()+1,arr.begin()+5);
    return 0;
}
schorsch312
  • 5,553
  • 5
  • 28
  • 57
Kishore Pula
  • 322
  • 2
  • 9

1 Answers1

3

Your final iterator needs to be one-past-the-end to work as you expect.

i.e.

arr.begin()+6

or why not just

arr.end()
acraig5075
  • 10,588
  • 3
  • 31
  • 50
  • thanks for directing to past-the-end link, I want to find the min element in intermediate-range that's why I won't be using arr.end() always – Kishore Pula Mar 13 '20 at 09:29
  • can you explain what is an empty range and why it is important to handle empty range? – Kishore Pula Mar 13 '20 at 09:38
  • @KishoreP empty range is a range with no elements. Why it is important? For example empty container. In this situation it would have `cont.begin()` == `cont.end()` and handling that is simple in any algo it would be passed to as a range. Otherwise you would have to check before calling or have additional flag passed. Which is error prone and unnecessary. And this is just one of the symptoms, there would be more. – Slava Mar 13 '20 at 12:17
  • Much appreciated @Slava :) – Kishore Pula Mar 14 '20 at 18:24