How to save position of min_element result?

11,411

Solution 1

You can use the distance provided by stl to find the position. You need to pass the iterator returned by min_element to it to get the position

See this example code

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

Solution 2

Use this:

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!

And in C++11 (if your compiler supports auto keyword), then this:

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
Share:
11,411

Related videos on Youtube

Marty
Author by

Marty

I'm an iOS developer on the eBay app.

Updated on June 04, 2022

Comments

  • Marty
    Marty almost 2 years

    How can I save the value of min_element? It says it's a forward iterator but I can't seem to figure out how to save (assign to a variable to) it. I want to be able to access it by location in the vector. All I can find is examples of using the actual element (using *min_element() ). I tried

    iterator< forward_iterator_tag, vector<string> > min_word_iterator = min_element(first_words_in_subvecs.begin(), first_words_in_subvecs.end());

    but that didn't work. I'm going to replace the element at that index with a different element.

  • GManNickG
    GManNickG over 12 years
    Or in C++11, auto minIt = ....
  • Marty
    Marty over 12 years
    how do i just get the int index of it?
  • Dean Burge
    Dean Burge over 12 years
    I fail to understand why there's a need to say "and in C++11 ...", or even why start off with the C++03 way. C++03 is past, Latin is dead, there are only 8 planets in our system, let's move on shall we?
  • Nawaz
    Nawaz over 12 years
    @wilhelmtell: C++03 is past only in theory (in language specification), many compilers still do not support many features of C++11. That is why I provided a C++03 solution as well.
  • Raghuram
    Raghuram over 12 years
    Refer to the example in the answer which i have posted with my answer
  • altroware
    altroware over 9 years
    Also min_element(myvec.begin(), myvec.end()) - myvec.begin() should be OK, does anyone know if it is different from distance(myvec.begin(),min_element(myvec.begin(),myvec.end()‌​)) ?