alryosha alryosha - 4 years ago 76
C++ Question

I don't get how find function works in C++

I would like to find a specific value index in a vector.

For example

#include<iostream>
#include<vector>

using namespace std;

int main()
{
vector<int> vec;

for(int i = 0; i < 10; i++)
vec.push_back(i);

int n = find(vec.begin(), vec.end(), 5);
printf("%d\n", n);

return 0;
}


I want to find '5' index in vector. but compiler said


error: no viable conversion from 'std::__1::__wrap_iter' to
'int'


But When I change

int n = find(vec.begin(), vec.end(), 5);


to

int n = find(vec.begin(), vec.end(), 5) - vec.begin();


it worked!!

why could the latter code be compiled but the former not??

please help me!!

Answer Source

Using std::find

std::find(vec.begin(), vec.end(), 5);

Returns an iterator to an element with value 5.

std::find(vec.begin(), vec.end(), 5) - vec.begin();

Returns the difference between the two iterators, and since you are subtracting vec.begin() you get the index.

Alternatively, you could use std::distance:

std::distance(vec.begin(), find(vec.begin(), vec.end(), 5));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download