在adjacent_find中使用greater_equal在排序序列中查找等效元素
Use greater_equal in adjacent_find to find equivalent elements in sorted sequence
在
算法std::adjacent_find
中使用std::greater_equal
在排序范围内查找等效(与相等相反(元素是UB吗?
如果未严格指定算法实现内部std::greater_equal<>{}(*prev, *next)
上一个和下一个元素的顺序,则答案可能是"否"。
std::container<int> c{1, 2, 3, 3, 4, 5};
assert(std::is_sorted(std::cbegin(c), std::cend(c));
assert(std::adjacent_find(std::cbegin(c), std::cend(c), std::greater_equal<int>{}) != std::cend(c));
std::adjacent_find
搜索谓词返回true
的两个连续元素。C++标准将行为记录为查找:
-
*i == *(i + 1)
没有参数pred
的重载 - 载
pred
pred(*i, *(i + 1)) != false
参数重第二个项目符号指定元素传递给谓词的顺序。
此示例实现(从 cppreference.com 复制(应该更清楚地说明这一点。
template<class ForwardIt, class BinaryPredicate>
ForwardIt adjacent_find(ForwardIt first, ForwardIt last, BinaryPredicate p)
{
if (first == last) {
return last;
}
ForwardIt next = first;
++next;
for (; next != last; ++next, ++first) {
if (p(*first, *next)) { // <- predicate called here
return first;
}
}
return last;
}
在 std::adjacent_find 算法中使用 std::less 来查找是 UB 吗 排序范围内的等效(与相等相反(元素?
它从来都不是未定义的行为,传递给std::adjacent_find
谓词的唯一限制是适当的类型,而不是修改其参数。
您正在查看此模板:
template< class ForwardIt, class BinaryPredicate>
ForwardIt adjacent_find( ForwardIt first, ForwardIt last, BinaryPredicate p );
这里p
p - 二进制谓词,如果元素应被视为相等,则返回 true。
只要满足算法的要求,这里就没有UB。如果对于您的问题,您必须将less
视为equal
那么它是完全有效的。
你没有 UB,但你想要的不是std::less
,1 < 2
,它会将迭代器返回到 1
。
你需要:
std::vector<int> c{1, 2, 3, 3, 4, 5};
assert(std::is_sorted(std::cbegin(c), std::cend(c));
auto it = std::adjacent_find(std::cbegin(c), std::cend(c),
[](auto lhs, auto rhs){
// For unsorted container, you would need
// return !(lhs < rhs) && !(rhs < lhs);
// but as container is sorted,
// we already have (lhs < rhs) || !(rhs < lhs)
return !(lhs < rhs);
});
// *it == 3; *(it+1) == 3;
相关文章:
- 使用堆查找第K个最大元素的时间复杂性
- 查找矩阵C++中每一列和每一行的最小和最大元素
- C++如何在向量中查找最常见的元素
- 查找两个排序向量中共有的元素
- 在对向量中查找元素的索引
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 查找矩阵中单元格的相邻元素
- 为什么使用数组元素查找最大数字的程序不起作用?
- 查找第一个数组中不存在的元素
- 查找最小的下一个更大的元素
- 在最小堆中查找最大元素
- 在向量中查找大于 0(或通常为 k)的最小元素的最佳方法是什么?
- set::find 查找不存在的元素
- 在集合中查找使用结构C++的元素
- 从斐波那契序列 c++ 中的数组中查找正确的元素时出错
- 用于查找数组中最大元素的出现次数的代码,给出分段错误
- 查找数组中指示性较大但数组中值较小的元素
- C++结构集无法按元素查找/擦除
- 如何在OpenCV中使用Matlab的512元素查找表数组?
- 使用数组的元素查找总和'k'