How to get the index of an element into a vector most efficiently?

I found binary_search() in STL which will return true if an element equivalent to val is found, and false otherwise. But it doesn't return index. As I knew binary search is one of the most efficient ways to find a number into an array/vector. But the STL binary search function is not giving me the index.

I found a code like following:

1
2
3
4
5
6
7
vector<int>::iterator indx=lower_bound(v.begin(),v.end(), num);

int pos=indx-v.begin();
if(indx == v.end() || *indx!=num)
    cout<<num<<" not found";
else
    cout<<num<<" found at "<<pos+1;


How much is the code efficient?

Is there any better way to find out the index which will take lest running time?
Do you really need index? Why not use iterators?
Also in your code pos != element index. It is off by one.

Your code is mostly fine. Here is example of how you could use iterator/index to change found value:
1
2
3
4
5
6
7
8
9
auto it = std::lower_bound(v.begin(), v.end(), num);
if(it == v.end() || *it != num) {
    std::cout << num << " not found\n"
} else {
    std::size_t ind = std::distance(v.begin(), it)
    std::cout << num << " was found at " << ind << '\n';
    std::cout << "Replacing with 0";
    *it = 0; // v[ind] = 0
}
Topic archived. No new replies allowed.