Finding the minimum element of a vector in C ++

I am trying to find the minimal element of a vector in C ++. I want to return both the value of the lowest element and the position of the index inside the vector. Here is what I tried

    auto minIt = std::min_element(vec.begin(), vec.end());
    auto minElement = *minIt;
       std::cout << "\nMinIT " << &minIt << " while minElement is " << minElement << "\n"; 

This returns the following

MinIT 8152610 while minElement is 8152610

How to get index i vec (i) where is the value?

+6
source share
1 answer

Return std::min_elementis an iterator that you confuse when using auto.

You can get its position in the vector using

std::distance(vec.begin(), std::min_element(vec.begin(), vec.end()));

which is more of a "standard C ++ library" than a less general

std::min_element(vec.begin(), vec.end()) - vec.begin();

although there are differences of opinion on the substance of any of them. See What is the most efficient way to get the std :: vector iterator index?

: http://en.cppreference.com/w/cpp/algorithm/min_element http://en.cppreference.com/w/cpp/iterator/distance

+12

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


All Articles