首页 > 解决方案 > 用于确定距离是否在“n”内的 STL 函数

问题描述

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

ifC非常大并且不是随机访问的,std::distance每次迭代都调用非常浪费,因为我们只需要确定距离是否小于 some 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
}

标签: c++stliteratorcontainers

解决方案


据我所知,标准库中没有任何东西可以自动执行此操作。但是,无论如何,您的解决方案都在正确的轨道上成为您想要的。您只需要稍作更改即可使其对随机访问迭代器更有效。

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

推荐阅读