Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

c++ - std::begin and std::end not working with pointers and reference why?

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].

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!
";
    }

   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!
";
    }

    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!
";
    }
}

Error:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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;

and begin and end will work on this exactly as they would work on first itself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...