如何将迭代器传递到std :: lower_bound()比较函数
How to to pass iterators to the std::lower_bound() comparison function?
在以下从cplusplus.com借来的声明中
template<class ForwardIterator, class T, class Compare>
ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& val, Compare comp);
comp()
应该类似于这样:
template<class T>
bool comp(const T& v1, const T& v2);
问题是我不想在那里传递值类型。我想将迭代器传递给它,然后将它们移动好吧,只需在签发之前默默地凝视它们。(更不用说 - 记录他们。(是否有任何解决方法?
当然,我可以用自己的迭代器编写自己的容器类,当然可以编写自己的std::lower_bound()
实现。这两个选项都令人不愉快。
来自 std::lower_bound
doc,可以读取 bool comp(const Type1 &a, const Type2 &b);
:
Type1
类型必须使ForwardIt
类型的对象被删除,然后隐式转换为Type1
。Type2
类型必须使T
类型的对象可以隐式转换为Type2
。
这意味着,std::lower_bound
将始终将comp
与范围内的元素称为左手侧参数,而value
将CC_14作为右手侧参数。如果您的搜索范围是连续范围(这意味着您正在处理std::vector
,std::array
,std::valarray
,std::string
,...或C-Style阵列(,则可以从范围的开始和comp
'S之间的距离设计一个迭代器左手参数:
auto v = std::vector<int>{0, 1, 2, 3, 4, 5};
auto comp = [&v](const int &lhs, const int &rhs)
{
auto it_lhs = cbegin(v) + std::distance(std::addressof(*cbegin(v)), &lhs);
return *it_lhs < rhs;
};
std::cout << *std::lower_bound(begin(v), end(v), 2, comp) << "n";
来自doc:
谓词函数的签名应等效于 以下:
comp()
0签名不需要具有
const &
,但是该功能不得 修改传递给它的对象。
这样您就不能,不应该这样做。std::lower_bound
具有特定的目的,并且不应以任何方式修改输入。为此目的编写自己的功能。
如果您仅需要索引,并且您的容器将其元素存储在线性,连续的内存块中,则可以执行此操作(例如,使用std::vector
(:
std::vector<...> vec;
...
const auto* firstElemPtr = &vec[0];
std::lower_bound(vec.begin(), vec.end(), key, [firstElemPtr](const auto& left, const auto& right) -> bool {
size_t index = &left - firstElemPtr;
// now do the comparison
});
- 空集"Out of bound iterator"
- 将张量的"lower diagonal"映射到矩阵,作为将矩阵的下三角形部分提取到向量的推广
- 为什么<<低;和 cout<<v.begin;单独给出错误,但 cout <<(lower.begin());没有给出任何错误,并使代码易于编译
- 使用多个文件时"array bound is not an integer constant before ']' token"
- "A reference may be bound only to an object",为什么"const int &ref = 3;"有效?
- 如何修复"reference cannot be bound to dereferenced null pointer"警告
- 当你有一个像 ::lower 这样的参数时,这在C++中是什么意思
- GCC 检测"subindex out of bound"错误
- 如果我没有得到分段错误,如何找到"index out of bound"
- 一个程序将字符串Upper char更改为Lower char得到错误
- std:: lower的行为在不同的语言环境中是如何变化的?
- 在main中声明Array之前,Array bound不是整型常量
- 获取错误"array bound is not an integer constant before ']' token"
- 如何在C或c++中获得与Java中的toLowerCase或Python中的string.lower()相同的结果
- 在运行时创建结构时"array bound is not an integer constant"