You cannot use min_element () correctly

I have a problem with min_element()in the title of an algorithm 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 displays the result 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 outputs “4” as output, whereas it should be “1”.

Can someone explain this please?

+4
source share
1 answer

Ranges in STL algorithms are half-open, i.e. The last item you specified is not included. for this reason, if you specify i=0and j=1, you consider only the first element.

+6
source

Source: https://habr.com/ru/post/1526115/


All Articles