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?
You'll have to write your own function, for example: