c ++搜索元素第一次看到位置的向量 [英] 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();
我想在排序向量中找到元素的第一个可见位置,并且我想使用 stl 来完成它.
示例:v = {1,1,2,6,7,8,8,8,8,9}
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
那么位置是 5.
Then position is 5.
看到这是一个排序向量,我不想使用find(),因为它每次都会从起点开始搜索.我想使用 binary_search() --- http://www.cplusplus.com/reference/algorithm/binary_search/,但 binary_search 将只返回 bool.
有什么建议吗?
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?
推荐答案
您可以使用 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
这篇关于c ++搜索元素第一次看到位置的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!