简体   繁体   中英

Finding minimum element of a vector in C++

I am trying to find the minimum element of a vector in C++. I wish to return both the value of the lowest element and the position of the index within the vector. Here is what I have 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 do I obtain the index i of vec(i) where this value is?

The return of std::min_element is an iterator , which you are obfuscating by your use of auto .

You can get the position of it in the vector using

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

which is more "C++ Standard Library"-esque than the less generic

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

although there are differences in opinion on the merits of either way. See What is the most effective way to get the index of an iterator of an std::vector?

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

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