Reputation: 65
Today I was trying to find a position of a element in a vector without binary search code and I found out that there is something as find() stl And I implemented it and it is compiling but it is not giving correct output
Here is my code :
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
vector<int> a(0);
a.push_back(6);
a.push_back(3);
a.push_back(9);
a.push_back(5);
a.push_back(1);
vector<int> :: iterator b;
b = find(a.begin() , a.end() , 3);
cout << (a.end() - b); // output is 4
return 0;
}
What should I do to get the position of any element in a vector ? Thanks
Upvotes: 1
Views: 152
Reputation: 23497
Try
std::cout << (b - a.begin());
Or, even better,
std::cout << std::distance(a.begin(), b);
(a.end() - b)
calculates the distance between the found element and the end of vector, which is really 4.
Upvotes: 7