sflee
sflee

Reputation: 1719

c++ search a vector for element first seen position

Solved
Thank you. This is solved. Here is the solution I used.

std::vector<int> v = {1,2,3,4,8,8,8,8,9,10}
auto p = std::lower_bound(v.begin(),b.end(),8);
int position = p - v.begin();



I want to find the first seen position of an element in a sorted vector and I want to use stl to do it.
Example: v = {1,1,2,6,7,8,8,8,8,9}

int position = my_fun(v.begin(),v.end(),8); // find the position of the first 8

Then position is 5.

Seen this is a sorted vector, I don't want to use find(), cause it will search from the starting point every time. I want to use binary_search() --- http://www.cplusplus.com/reference/algorithm/binary_search/, but binary_search will return bool only.
Any suggestions?

Upvotes: 2

Views: 158

Answers (4)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

You can should method std::equal_range

For example

auto p = std::equal_range( v.begin(), v.end(), 8 );

if ( p.first != p.second ) 
{
   std::cout << "Position of the first element with value 8 is " 
             << std::distance( v.begin(), p.first )
             << std::endl;
}

Or you can use std::lower_bound:

auto it = std::lower_bound( v.begin(), v.end(), 8 );

if ( it != v.end() && *it == 8 ) 
{
   std::cout << "Position of the first element with value 8 is " 
             << std::distance( v.begin(), it )
             << std::endl;
}

Upvotes: 1

timrau
timrau

Reputation: 23058

You could use lower_bound().

vector<int>::const_iterator pos = std::lower_bound(v.begin(), v.end(), 8);
if (pos != v.end() && *pos == 8)
    return std::distance(v.begin(), pos);
return -1; // not found

Upvotes: 2

Profan
Profan

Reputation: 171

int item = 8;
const auto posItr = std::lower_bound(std::begin(v), std::end(v), item);
return (posItr != std::end(stuff) && *posItr == item) ? std::distance(std::begin(stuff), posItr) : -1;

Why I used std::begin and std::end instead of the container one:

Upvotes: 1

abraabra
abraabra

Reputation: 474

You should use the lower_bound function.

Upvotes: 1

Related Questions