RDK
RDK

Reputation: 153

Can't use min_element() properly

I am having a problem with the min_element() in the algorithm header in C++.

The code is as follows:

int a[5] = {4, 1, 2, 3, 4};

for (int j = n - 1; j >= 0; j--) {
    for (int i = 0; i <= j; i++) {
        int *lowest = min_element(a+i, a+j);   //get min element in range
        cout << "A[" << i << "] to A[" << j << "]"
             << "lowest =" << *lowest << endl;
    }
}

it gives output as below

A[0] to A[4]lowest =1
A[1] to A[4]lowest =1
A[2] to A[4]lowest =2
A[3] to A[4]lowest =3
A[4] to A[4]lowest =4
A[0] to A[3]lowest =1
A[0] to A[2]lowest =1
"A[0] to A[1]lowest =4"
A[0] to A[0]lowest =4

For i=0 and j=1 it prints '4' as output whereas it should be '1'.

Can anybody explain it please?

Upvotes: 4

Views: 112

Answers (1)

Matteo Italia
Matteo Italia

Reputation: 126937

Ranges in STL algorithms are half-open, i.e. the last element you specify isn't included; for this reason, if you specify i=0 and j=1 you are considering only the first element.

Upvotes: 6

Related Questions