1

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

Zig Razor
  • 2,907
  • 2
  • 8
  • 27
  • 1
    Please read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) as well as [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Some programmer dude Jan 05 '20 at 19:14

1 Answers1

7

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.

Daniel Langr
  • 18,256
  • 1
  • 39
  • 74