[英]Using std::begin and std::end with array with run-time size
对于编码测试,我有以下 function:
static bool exists (int ints[], int size, int k)
如果k
在ints
中,目标是返回true
,否则返回false
。
使用 std 库,可以这样做:
static bool exists (int ints[], int size, int k) {
return std::binary_search(std::begin(ints), std::end(ints), k);
}
但是,如果编译器知道大小,则std::begin()
仅适用于 C 风格的 arrays,据我所知。 我不确定为什么会这样。
有没有办法在不编写自定义迭代器来处理它的情况下实现我想要的? 甚至可以编写这样的迭代器吗?
使用std::vector
不是一个选项,因为我无法更改 function 定义。 在调用std::binary_search()
之前将数组复制到std::vector
似乎也浪费了 CPU 时间。
您不能随意使用std::begin()
或std::end()
,因为正如 Andrieux 在评论中指出的那样,函数参数列表中似乎是数组类型的只是一个指针。 function 的第二个参数是元素的数量这一事实证实了这一点。 如果std::end()
所需的信息存在于ints[]
中,则不需要这样的论点。
然而,正如我在撰写本文时看到的前四条评论中的每一条都指出的那样,传入的指针是一个迭代器。 事实上,普通指针具有随机访问迭代器的所有属性。
所以,是的,你不需要想出你自己的迭代器。 只需按照评论者的指示使用传入的指针。
static bool exists (int ints[], int size, int k) {
return std::binary_search(ints, ints + size, k);
}
然而,调用std::binary_search()
是正确的做法,只有当ints[]
的元素被排序以便std::binary_search()
可以工作时。 您没有在您的帖子中提到 state。
至于是否可以像您想要的那样编写迭代器,答案是“是”,但这是不必要的,因为指针已经是输入到std::binary_search()
的正确迭代器。
你是对的,在正文中使用std::vector
会浪费时间。
如果两个输入数组都是有序的,并且 function 的签名改为
template<int size> bool exists (int (&ints)[size], int k);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.