Hi,
I know the return value of generic search algorithm "find()" is of iterator type. Now how can I output the return value as numeric type? For example:

short myArray[4] = {2,1,3,7};
vector<short>mVec(myArray,myArray+4);
vector<short>::iterator found;
found = find(mVec.begin(),mVec.end(),2);

In this code the variable found will be assigned the "mVec.begin", but can I obtain its numeric counter part,say, 0 instead? How? Thank u in advance.

Thank you jencas,
I think there is something not so explicit in my presentation. Sorry for that. In fact,what I want to get is the numeric index of the elements those are found. It seems you have shown me how to obtain the value that has been found,however. This may trivial since the value is just an input parameter of find().

found - m_vec.begin();

example:

#include <vector>
#include <algorithm>

using namespace std;

int main()
{
  vector<int> v;
  v.push_back(5);
  v.push_back(1);
  v.push_back(9);
  v.push_back(3);
  
  vector<int>::iterator i = find(v.begin(), v.end(), 9);
  vector<int>::difference_type index = i - v.begin();

  cout << index << endl;
}

prints: 2

I think that you are after the distance algorithm e.g.

std::vector<int> A;
// ... stuff here
vector<int>::iterator i = find(A.begin(), A.end(), 9);
// can use std::vector<int>::difference_type 
// or static_cast to int etc.
long int index=std::distance(v.begin(),i);

Note it work with std::list and other containers with a reversible iterator.

The advantage is that distance works with list,map etc.

Some care has to be taken when using const_iterator, since you will need to case begin() and end() to the correct type. Which is a pain. [Normally cheat an implicitly cast by assignment e.g.

// long horrible way
long int x=std::distance(i,
       static_cast<std::vector<int>::const_iterator>(A.end()));
// other way
std::vector<int>::const_iterator ac,ec;
ec=A.end();
long int y = std::distance(ac,ec);
This article has been dead for over six months. Start a new discussion instead.