如何保存min_element结果的位置?

3
我该如何保存min_element的值?它被称为前向迭代器,但我似乎无法弄清楚如何保存(赋值给变量)。我希望能够通过向量中的位置访问它。我只能找到使用实际元素的示例(使用* min_element())。我尝试了以下代码: auto min_word_iterator = min_element(first_words_in_subvecs.begin(), first_words_in_subvecs.end()); 但是那不起作用。我将用不同的元素替换该索引处的元素。
3个回答

5
请使用以下内容:
std::vector<T>::iterator minIt = std::min_element(v.begin(),v.end());
//where T is the type of elements in vector v.

T minElement = *minIt; //or T & minElement = *minIt; to avoid copy!

如果您的编译器支持auto关键字,那么在 C++11 中,可以这样写:

auto minIt = std::min_element(v.begin(), v.end());
//type of minIt will be inferred by the compiler itself

T minElement = *minIt; //or auto minElement = *minIt;
                       //or auto & minElement = *minIt; to avoid copy

在C++11中,auto minIt = ... - GManNickG
我不明白为什么需要说“在C++11中...”,甚至为什么要从C++03的方式开始。C++03已经过去,拉丁语已死,我们的系统只有8个行星,让我们继续前进吧? - wilhelmtell
5
C++03 在语言规范中已经过时,但许多编译器仍不支持 C++11 的许多功能。这就是为什么我提供了一个 C++03 的解决方案。 - Nawaz

4
你可以使用stl提供的distance函数来查找位置。你需要将min_element返回的迭代器传递给它以获取位置。
请看此示例代码。
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
using namespace std;

int main () {
  vector<int> myvec;
  int i = 0;
  for (i=8; i>0; i--)
  {
      myvec.push_back (i*10);
  }

  for (i=0; i<8; i++)
  {
      cout<<"At pos :"<<i<<"|val is:"<<myvec.at(i)<<endl;
  }

  int min_pos = distance(myvec.begin(),min_element(myvec.begin(),myvec.end()));
  cout << "The distance is: " << min_pos << "|value is "<<*min_element(myvec.begin(),myvec.end())<<endl;

  return 0;
}

我该如何仅获取它的整数索引? - Marty
请参考我回答中附带的示例。 - Raghuram
此外,min_element(myvec.begin(), myvec.end()) - myvec.begin() 应该没问题,有人知道它是否与 distance(myvec.begin(),min_element(myvec.begin(),myvec.end())) 不同吗? - altroware

0

当您有两个随机访问迭代器时,通常可以从一个中减去另一个以找到它们之间的距离。因此,一旦您获得了迭代器 it ,您可以使用 it-my_vector.begin()查找其引用元素的索引。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接