Loe*_*rio 4 c++ stl vector binary-search
如果我有以下向量{10 10 10 20 20 20 30 30}并且我希望函数返回整数的位置= X或直接返回X之后的较小元素,例如,如果我正在搜索11我想要返回2的函数,因为第二个元素(10)是向量中第一个小于11的元素.
我尝试使用lower_bound,但这不起作用.
int myints[] = {10,20,30,30,20,10,10,20};
vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20
vector<int>::iterator low,up;
sort (v.begin(), v.end());                // 10 10 10 20 20 20 30 30
low=lower_bound (v.begin(), v.end(), 11); //
up= upper_bound (v.begin(), v.end(), 11); //
cout << "lower_bound at position " << int(low- v.begin()) << endl;
cout << "upper_bound at position " << int(up - v.begin()) << endl;
return 0;
此代码输出: 
lower_bound at position 3
upper_bound at position 3
cppreference通知我 std::lower_bound
返回指向范围[first,last]中不小于value的第一个元素的迭代器
和 std::upper_bound
返回指向范围[first,last]中第一个元素的迭代器,该元素大于value
在这种情况下,给定一个包含10 10 10 20 20 20 30 30I 的向量,可以期望两个函数指向第一个20,它位于向量中的位置3,并且确实是两次得到的结果.如果您反而要求20,std::lower_bound将返回指向20向量中第一个的迭代器(位置3)......第一个数字不小于20,并且在请求时获得相同的结果11.但在这种情况下,std::upper_bound将返回指向第一个30(位置6)的迭代器,这是第一个大于20的值.
只需将迭代器移回一个以获得小于目标数的最后一个值,这std::prev是一种方法.