std :: begin和std :: end不使用指针和引用为什么?

Rup*_*av. 6 c++ stl c++11

为什么std :: begin()std :: end()适用于数组而不是指针[几乎是数组]和数组的引用[它是原始数组的别名].

在我挠头15分钟后,我无法在谷歌中得到任何东西.

下面只有第一个案例,而不是第二个和第三个,这可能是什么原因?

#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";
    }
}
Run Code Online (Sandbox Code Playgroud)

错误:

error: no matching function for call to ‘begin(int&)’
  if (std::find(std::begin(*second), std::end(*second), 5) != std::end(*second)) {
                                  ^
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 10

只给出一个指向数组开头的指针,就无法确定数组的大小; 所以begin并且end不能用于指向动态数组的指针.

std::vector如果您想要一个知道其大小的动态数组,请使用.作为奖励,这也将修复您的内存泄漏.

第三种情况失败,因为您再次使用(引用)指针.您可以使用对数组本身的引用:

int (&refOfFirst)[3] = first;
Run Code Online (Sandbox Code Playgroud)

或者,为了避免必须指定数组大小:

auto & refOfFirst = first;
Run Code Online (Sandbox Code Playgroud)

beginend将在这方面的工作,正是因为他们将在工作first本身.

  • "只给出一个指向数组开头的指针,就没有办法确定数组的大小;所以开始和结束不能用于指向动态数组的指针.",好吧,至少有一个`begin`.我见过通用编程案例,其中`T*begin(T*ptr){return ptr;}`有意义存在. (3认同)