Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index of minimum element in a std::list

If I have a std::vector<int>, I can obtain the index of the minimum element by subtracting two iterators:

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

However, with containers that don't have random access iterators, for example a std::list<int>, this doesn't work. Sure, it is possible to do something like

int min_index = std::difference(l.begin(), std::min_element(l.begin(), l.end()));

but then I have to iterate twice through the list.

Can I get the index of the element with the minimum value with STL algorithms by only iterating once through the list or do I have to code my own for-loop?

like image 519
user1181282 Avatar asked Mar 13 '12 16:03

user1181282


People also ask

How do you find the minimum value in C++?

std::min in C++ std::min is defined in the header file <algorithm> and is used to find out the smallest of the number passed to it. It returns the first of them, if there are more than one.

How do you find the smallest value of a vector?

To find a smallest or minimum element of a vector, we can use *min_element() function which is defined in <algorithm> header. It accepts a range of iterators from which we have to find the minimum / smallest element and returns the iterator pointing the minimum element between the given range.


1 Answers

You'll have to write your own function, for example:

template <class ForwardIterator>
  std::size_t min_element_index ( ForwardIterator first, ForwardIterator last )
{
  ForwardIterator lowest = first;
  std::size_t index = 0;
  std::size_t i = 0;
  if (first==last) return index;
  while (++first!=last) {
    ++i;
    if (*first<*lowest) {
      lowest=first;
      index = i;
    }
  }
  return index;
}
like image 65
Robᵩ Avatar answered Oct 02 '22 05:10

Robᵩ