问题
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?
回答1:
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
回答2:
You should use the lower_bound
function.
回答3:
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:
- http://www.codeproject.com/Articles/570638/Ten-Cplusplus11-Features-Every-Cplusplus-Developer#beginend
回答4:
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;
}
来源:https://stackoverflow.com/questions/21977703/c-search-a-vector-for-element-first-seen-position