If I have std::vector<int>
, I can get 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 do not have random access iterators, like a std::list<int>
, this does not work. Of course, you can do something like
int min_index = std::difference(l.begin(), std::min_element(l.begin(), l.end()));
but then I have to repeat twice through the list.
Can I get the index of an element with a minimum value using STL algorithms, only repeating once through a list or do I need to encode my own for-loop?
source share