Marty
Marty

Reputation: 6174

How to save position of min_element result?

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.

Upvotes: 3

Views: 11567

Answers (3)

Raghuram
Raghuram

Reputation: 3967

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

Upvotes: 4

Komi Golov
Komi Golov

Reputation: 3471

When you have two random access iterators, you can generally subtract one from the other to find the distance between them. Thus, once you've got the iterator it, you can find the index of the element it refers to with it - my_vector.begin().

Upvotes: 1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361362

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

Upvotes: 5

Related Questions