Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding minimum element of a vector in C++

Tags:

c++

vector

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?

like image 699
PeterSM Avatar asked Mar 01 '17 13:03

PeterSM


1 Answers

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

like image 96
Bathsheba Avatar answered Sep 19 '22 22:09

Bathsheba