Index of minimum element in a std::list

怎甘沉沦 提交于 2019-12-09 16:41:22

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/9687957/index-of-minimum-element-in-a-stdlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!