std :: begin和std :: end无法使用指针并引用原因? [英] std::begin and std::end not working with pointers and reference why?
问题描述
为什么 std :: begin()和 std :: end()与数组一起使用,但不适用于指针[几乎是数组]和引用数组[原始数组的别名]。
Why std::begin() and std::end() works with array but not pointer[which is almost array] and reference of array [which is alias of original array].
ing了15分钟后,我无法在Google上找到任何东西。
After scratching my head for 15 min i am not able to get anything in google.
只有第一种情况有效,而不是第二种和第三种情况,这可能是什么原因?
Below only first case works, not second and third, what could be the reason for this?
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
int first[] = { 5, 10, 15 }; // Fist Case
if (std::find(std::begin(first), std::end(first), 5) != std::end(first)) {
std::cout << "found a 5 in array a!\n";
}
int *second = new int[3]; // Second Case
second[0] = 5;
second[1] = 10;
second[2] = 15;
if (std::find(std::begin(second), std::end(second), 5) != std::end(second)) {
std::cout << "found a 5 in array a!\n";
}
int *const&refOfFirst = first; // Third Case
if (std::find(std::begin(refOfFirst), std::end(refOfFirst), 5) != std::end(refOfFirst)) {
std::cout << "found a 5 in array a!\n";
}
}
错误:
error: no matching function for call to ‘begin(int&)’
if (std::find(std::begin(*second), std::end(*second), 5) != std::end(*second)) {
^
推荐答案
只给出一个指向数组开头的指针,无法确定数组的大小。因此开始
和 end
无法处理指向动态数组的指针。
Given just a pointer to the start of an array, there's no way to determine the size of the array; so begin
and end
can't work on pointers to dynamic arrays.
如果要一个知道其大小的动态数组,请使用 std :: vector
。作为奖励,这也将解决您的内存泄漏。
Use std::vector
if you want a dynamic array that knows its size. As a bonus, that will also fix your memory leak.
第三种情况失败了,因为再次使用了指针(对指针的引用)。您可以使用对数组本身的引用:
The third case fails because, again, you're using (a reference to) a pointer. You can use a reference to the array itself:
int (&refOfFirst)[3] = first;
或者,以避免指定数组大小:
or, to avoid having to specify the array size:
auto & refOfFirst = first;
和开始
和 end
会像在 first
本身上那样工作。
and begin
and end
will work on this exactly as they would work on first
itself.
这篇关于std :: begin和std :: end无法使用指针并引用原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!