Sudheera Y S
Sudheera Y S

Reputation: 65

find() stl in vector in c++

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

Answers (1)

Daniel Langr
Daniel Langr

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

Related Questions