c++ - std::begin and std::end not working with pointers and reference why? -
why std::begin() , std::end() works array not pointer[which array] , reference of array [which alias of original array].
after scratching head 15 min not able in google.
below first case works, not sec , third, reason 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 5 in array a!\n"; } int *second = new int[3]; // sec 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 5 in array a!\n"; } int *const&refoffirst = first; // 3rd case if (std::find(std::begin(refoffirst), std::end(refoffirst), 5) != std::end(refoffirst)) { std::cout << "found 5 in array a!\n"; } }
error:
error: no matching function phone call ‘begin(int&)’ if (std::find(std::begin(*second), std::end(*second), 5) != std::end(*second)) { ^
given pointer start of array, there's no way determine size of array; begin
, end
can't work on pointers dynamic arrays.
use std::vector
if want dynamic array knows size. bonus, prepare memory leak.
the 3rd case fails because, again, you're using (a reference to) pointer. can utilize reference array itself:
int (&refoffirst)[3] = first;
or, avoid having specify array size:
auto & refoffirst = first;
and begin
, end
work on work on first
itself.
c++ c++11 stl
No comments:
Post a Comment