简体   繁体   中英

Why is min_element() returning the index of the minimum element, instead of an iterator?

min_element() is supposed to return a pointer pointing to the minimum element in a array or vector, but here it is returning a position of the element with minimum value. Why is this happening? Sorry for this silly question i am a beginner.

int n; cin>>n;
vector<int> arr(n);
for(int i=0;i<n;i++)
    cin>>arr[i];

int minElementIndex = min_element(arr.begin(),arr.end()) - arr.begin();
cout<<minElementIndex;

min_element returns an iterator (not necessarily a pointer) to the element. It does so here as well.

But you are not printing the return value of the min_element call. You are first subtracting the iterator to the beginning of arr from it ( - arr.begin() ).

Subtracting (random-access) iterators of a container (or pointers into the same array) results in an integer with value equal to the distance between the iterators or pointer. So if you subtract an iterator to the beginning, you get the index of the element as integer.

You are subtracting a pointer from another in your call to min_element . Try this approach rather:

    int index;
    int n; cin >> n;
    vector<int> arr(n);
    for (int i = 0; i < n; i++)
        cin >> arr[i];

    int minElementValue = *std::min_element(arr.begin(), arr.end());


    for (int i = 0; i < n; i++) {
        if (arr[i] == minElementValue) {
            index = i;


        }
    }

    cout << minElementValue << ":" ;
    cout << "  " << index;


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM