STL功能用于确定距离是否在n`中
STL function for determining if distance is within `n`
假设我有一些元素的容器C
和两个迭代器it1
和it2
(it1 <= it2
WLOG(。如果std::distance(it1, it2) <= n
,我想执行一些操作f
。此外,it1
和it2
在循环中正在发生变化(可能是随机的(,我需要检查每次迭代的距离。
如果C
非常大,而不是随机访问,则在每次迭代中调用std::distance
非常浪费,因为我们只需要确定距离是否小于某些n
。编写一些功能是相当微不足道的,这将需要两个迭代器和一个整数,然后返回两者之间的距离是否在提供的整数内,但是我想知道是否有某种方法可以使用STL来完成此任务。
本质上,我正在寻找的是以下功能的STL版本:
template <class ForwardIt>
bool is_within(ForwardIt it1, ForwardIt it2, int n) {
int i = 0;
while (i++ <= n)
if (it1++ == it2) return true;
return false
}
据我所知,标准库中没有什么可以自动执行此操作的。但是,您的解决方案是正确的轨道,无论如何都是您想要的。您只需要进行较小的更改即可使其更有效地用于随机访问迭代器。
template<typename Iter>
bool is_within(Iter a, Iter b, std::size_t n)
{
// if we're a random access iterator, use the (faster) std::distance() method
if constexpr (std::is_same_v<typename std::iterator_traits<Iter>::iterator_category, std::random_access_iterator_tag>)
{
return std::distance(a, b) <= n;
}
// otherwise go the long way around with short circuiting on n
else
{
for (; n > 0 && a != b; --n, ++a);
return a == b;
}
}
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 检查输入是否不是整数或数字
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 此代码是否违反一个定义规则
- 是否需要删除包含对象的"pair"?
- 是否可以从int转换为enum类类型
- 无论条件是否为true,if总是在c++中执行
- 如何找到大小'x'数组是否完全填充,在C++?
- 检查值是否在集合p1和p2中,但不在p3中
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 是否可以在单目ORB-SLAM2中获得距离缩放
- STL功能用于确定距离是否在n`中
- 是否有C 功能来计算两个索引之间的距离
- 是否有具有对数时间插入、删除和查找(带距离)的排序数据结构
- 在3D中,确定射线是否与三角形碰撞以及到碰撞点的距离