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?
std::list
? – Emasculatelist::iterator
and keeps track of its index as it goes. It would have limited use, since inserting/removing elements from the container would invalidate the indexes stored in your iterators, but you could usemin_element
and other algorithms on it, then grab the index out of the return value. – Rizzostd::set
or sort your container and always know where the minimum element is ... – Beckfordlist
is probably the wrong data structure for the job. – Houdinistd::vector
instead the index would be preserved upon insertion and you would only have to perform O(1) comparisons every time instead of O(n). I don't think that you can do it with std::list if elements can be added /removed to the list . – Stumerstd::distance
example, while theoretically slower than a single pass for-loop, is pretty much guaranteed to be correct on the first try. – Maddeningstd::list
is the output of some blackbox process, which he may not modify, then we this is a problem to consider. – Stumer