STL功能用于确定距离是否在n`中

STL function for determining if distance is within `n`

本文关键字:是否 距离 功能 用于 STL      更新时间:2023-10-16

假设我有一些元素的容器C和两个迭代器it1it2(it1 <= it2 WLOG(。如果std::distance(it1, it2) <= n,我想执行一些操作f。此外,it1it2在循环中正在发生变化(可能是随机的(,我需要检查每次迭代的距离。

如果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;
    }
}