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

时间:2014-11-13 12:57:12

标签: c++ c++11 stl

为什么 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";
    }
}

错误:

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

1 个答案:

答案 0 :(得分:10)

只给出一个指向数组开头的指针,就无法确定数组的大小;因此beginend无法处理指向动态数组的指针。

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

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

int (&refOfFirst)[3] = first;

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

auto & refOfFirst = first;

begin以及end将完全按照first本身的方式运作。

相关问题