Minimum element index in std :: list

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?

+6
source share
1 answer

You will need 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; } 
+1
source

Source: https://habr.com/ru/post/910612/


All Articles