6

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?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
PeterSM
  • 143
  • 2
  • 6

1 Answers1

13

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

Community
  • 1
  • 1
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Thank you for your brilliant answer! Could you expand it to deal with two dimensional vectors too? I will update my question via an edit! – PeterSM Mar 01 '17 at 16:44
  • 1
    It's best to ask a new question from scratch. Methinks the answer will be very different. – Bathsheba Mar 01 '17 at 16:53