【问题标题】:Using std::begin and std::end with array with run-time size将 std::begin 和 std::end 与具有运行时大小的数组一起使用
【发布时间】:2021-07-30 17:58:30
【问题描述】:

对于编码测试,我有以下功能:

static bool exists (int ints[], int size, int k)

如果kints 中,则目标是返回true,否则返回false

使用标准库,可以做到这一点:

static bool exists (int ints[], int size, int k) {
    return std::binary_search(std::begin(ints), std::end(ints), k);
}

但是,std::begin() 仅适用于 C 样式的数组,前提是编译器知道大小,从我收集到的内容。不过我不知道为什么会这样。

有没有办法在不编写自定义迭代器来处理它的情况下实现我想要的?有可能写出这样的迭代器吗?

使用std::vector 不是一个选项,因为我无法更改函数定义。在调用std::binary_search() 之前将数组复制到std::vector 似乎也是在浪费CPU 时间。

【问题讨论】:

  • 你必须使用std::beginstd::end吗?您可以使用std::binary_search(ints, ints + size, k); 获得此效果。或者std::array/std::vector
  • 哇,我没想到你可以做 std::binary_search(ints, ints + size, k);感谢您的回答。
  • std::beginstd::end 存在之前,我们就是这样做的。
  • 数组类型函数参数是继承自C的一个大谎言。它们实际上只是指向第一个元素的指针。这是指针和数组之间经常混淆的原因之一。正如您所注意到的,std::beginstd::end 不适用于指针。但是指针是一种有效的迭代器,因此您可以使用指针而不是 std::beginstd::end,只要这些指针引用连续范围的元素即可。所以你可以使用ints 作为begin 迭代器和ints + size 作为end 迭代器。

标签: c++ arrays iterator


【解决方案1】:

您不能随意使用std::begin()std::end(),因为正如Andrieux 在评论中指出的那样,函数的参数列表中看似数组类型的只是一个指针。函数的第二个参数是元素的数量这一事实证实了这一点。如果std::end() 所需的信息存在于ints[] 中,则不需要这样的论点。

然而,正如我在撰写本文时看到的前四个 cmets 中的每一个所指出的,传入的指针是一个迭代器。事实上,普通指针具有随机访问迭代器的所有属性。

所以,是的,您不需要提出自己的迭代器。只需按照评论者的指示使用传入的指针即可。

static bool exists (int ints[], int size, int k) {
  return std::binary_search(ints, ints + size, k);
}

然而,调用std::binary_search() 是正确的做法,只有当ints[] 的元素被排序以便std::binary_search() 可以工作时。您没有在帖子中说明这一点。

至于是否可以编写您想要的迭代器,答案是“是”,但没有必要,因为指针已经是输入到std::binary_search() 的正确迭代器。

你说得对,在正文中使用std::vector 会浪费时间。

如果两个输入数组都是有序的,而函数的签名却是

template<int size> bool exists (int (&ints)[size], int k);

【讨论】:

  • 请注意,template&lt;int size&gt; 解决方案很棒,但只有在 size 是编译时常量时才有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-04
  • 2011-08-20
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
  • 2016-02-08
相关资源
最近更新 更多