c++ - 用于确定距离是否在“n”内的 STL 函数
问题描述
假设我有一些C
元素容器和两个迭代器it1
和it2
( it1 <= it2
wlog) 。如果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
}
解决方案
据我所知,标准库中没有任何东西可以自动执行此操作。但是,无论如何,您的解决方案都在正确的轨道上成为您想要的。您只需要稍作更改即可使其对随机访问迭代器更有效。
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;
}
}
推荐阅读
- mongodb - 在 Ubuntu 20.04 上启用多个 mongodb 实例
- wpf - 如何离线使用 Windows.Media.SpeechRecognition?
- angular - 我应该使用 Spring 安全角色基础授权还是 Angular Route Gards 或两者兼而有之?
- ethereum - 警告!合约执行过程中遇到的错误 [Reverted] = EIP 1559 之后的ETH主链
- android - Android 中 KEYCODE_APP_SWITCH 的 HID 用法?
- firebase - 如何通过 gcloud 将 tflite 文件上传到 firebase 测试实验室设备?
- scala - 当 NullType 在 StructType 中时,将空值写入 Spark 中的 Parquet
- java - pdfbox:java.lang.NumberFormatException:对于输入字符串:“1#1”
- apache-spark - Amazon EMR 未分配所有请求的内存
- ffmpeg - 将媒体文件转换为 mp4 时 ffmpeg -i 不起作用