std :: list中的最小元素索引 [英] Index of minimum element in a std::list

查看:421
本文介绍了std :: list中的最小元素索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 std :: vector< int> ,我可以通过减去两个迭代器来获得最小元素的索引:

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();

但是,对于没有随机访问迭代器的容器,例如 std :: list< int> ,这不起作用。当然,有可能做类似

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.

我可以通过在列表中迭代一次来获得具有STL算法的最小值的元素的索引,还是我必须编写自己的for循环?

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:

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

这篇关于std :: list中的最小元素索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆