[英]Search around values in std::vector
std::vector<int> v1 = { 0,48000 };
e1 = left(v1,0); // should return first item's iterator
e1 = left(v1,10000); // should return first item's iterator
e1 = left(v1,20000); // should return first item's iterator
e1 = left(v1,48000); // should return the second item's iterator
e1 = right(v1,0); // should return first
e1 = right(v1,10000); // should return second
e1 = right(v1,48000); // should return second
e1 = right(v1,60000); // should return end()
My problem is how to implement functions left
and right
.我的问题是如何实现功能
left
和right
。 std::upper_bound and std::lower_bound don't seem to help: std::upper_bound 和 std::lower_bound 似乎没有帮助:
auto l1 = std::lower_bound(v1.begin(), v1.end(), 0); // 0
l1 = std::lower_bound(v1.begin(), v1.end(), 14000); // 48000
l1 = std::lower_bound(v1.begin(), v1.end(), 38000);
l1 = std::lower_bound(v1.begin(), v1.end(), 48000);
l1 = std::lower_bound(v1.begin(), v1.end(), 58000); // end()
auto l1 = std::upper_bound(v1.begin(), v1.end(), 0); // 48000
l1 = std::upper_bound(v1.begin(), v1.end(), 14000); // 48000
l1 = std::upper_bound(v1.begin(), v1.end(), 38000); // 48000
l1 = std::upper_bound(v1.begin(), v1.end(), 48000); // end()
l1 = std::upper_bound(v1.begin(), v1.end(), 58000); // end()
Basically, in a container which contains some sorted values, I want, by specifying an value that does not exist in the container, to take what's left and what's right on it (without of course searching manually in a loop if possible).基本上,在包含一些已排序值的容器中,我希望通过指定容器中不存在的值来获取其上剩下的内容和正确的内容(当然,如果可能,无需在循环中手动搜索)。
Your right()
function finds an iterator pointing to the first element greater than or equal to a given value while the left()
function returns an iterator pointing to the first element lesser than or equal to a given value.您的
right()
function 找到一个指向大于或等于给定值的第一个元素的迭代器,而left()
function 返回一个指向小于或等于给定值的第一个元素的迭代器。
So, your right()
function should use std::lower_bound()
while your left()
function should do the same but with a greater-than comparator and with reverse iterators.所以,你的
right()
function 应该使用std::lower_bound()
而你的left()
function 应该做同样的事情,但使用大于比较器和反向迭代器。
Try the following:尝试以下操作:
#include <algorithm>
#include <utility>
#include <iterator>
#include <vector>
template <typename T>
typename std::vector<T>::const_iterator left(std::vector<T> const& v, T const& val) {
return v.empty() || val < v.front() || val > v.back()
? v.end()
: std::next(std::lower_bound(v.rbegin(), v.rend(), val, std::greater<T>())).base();
}
template <typename T>
typename std::vector<T>::const_iterator right(std::vector<T> const& v, T const& val) {
return v.empty() || val < v.front()
? v.end()
: std::lower_bound(v.begin(), v.end(), val);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.