tags:

views:

1331

answers:

3

Hi, im trying to locate the position of the minimum value in a vector, using STL find algorithm (and the min_element algorithm), but instead of returning the postion, its just giving me the value. E.g, if the minimum value is it, is position will be returned as 8 etc. What am I doing wrong here?

int value=*min_element(v2.begin(),v2.end());
cout<<"min value at position "<< *find(v2.begin(),v2.end(),value);
+15  A: 

min_element already gives you the iterator, no need to invoke find (additionally, it's inefficient because it's twice the work). Use distance or the - operator:

cout << "min value at " << min_element(v2.begin(), v2.end()) - v2.begin();
Konrad Rudolph
+11  A: 

Both algorithms you're using return iterators. If you dereference an iterator, you get the object which is "pointed" by this iterator, which is why you print the value and not the position when doing

cout<<"min value at position "<< *find(v2.begin(),v2.end(),value);

An iterator can be seen as a pointer (well, not exactly, but let's say so for the sake of simplicity); therefore, an iterator alone can't give you the position in the container. Since you're iterating a vector, you can use the minus operator, as Konrad said:

cout << "min value at " << min_element(v2.begin(), v2.end()) - v2.begin();

,but I would recommend using the std::distance algorithm, which is much more flexible and will work on all standard containers:

cout << "min value at " << distance(v2.begin(), min_element(v2.begin(), v2.end()));
Luc Touraille
+2  A: 

The short answer to what you think you asked with "How do I determine position in std::vector<> given an iterator from it?" is the function std::distance.

What you probably meant to do, however, was to get the value for the iterator, which you get by dereferencing it:

using namespace std;
vector<int>::const_iterator it = min_element(v2.begin(), v2.end());
cout << "min value at position " << distance(v2.begin(), it) << " is " << *it;
Johann Gerell