2

I am reading the C++ Primer 5th Edition book. Now and then, the author uses the functions begin and end.

For example:

int ia[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

int (*p)[4] = begin(ia);

However, I get the error:

error: ‘begin’ was not declared in this scope

I am running gcc 4.9.2, and I use the following command to compile:

g++ -std=c++11 main.cpp
Afonso Matos
  • 2,406
  • 1
  • 20
  • 30

3 Answers3

11

The author probably has a declaration like using namespace std; or using std::begin;. You need to type std::begin without one of those. You might also need to #include<iterator>.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
4

You need to wrap it in the std scope, the function is std::begin

int (*p)[3] = std::begin(ia);

Likely in the text, the author had a using directive at the top of the code.

using namespace std;

I would discourage you from using the latter method.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

You have to include header <iterator> where function begin is declared

#include <iterator>

and if you did not include the using directive

using namespace std;

then you have to use a qualified name for begin

int ( *p )[4] = std::begin( ia );

or

auto p = std::begin( ia );

In fact statement

int ( *p )[4] = std::begin( ia );

is equivalent to

int ( *p )[4] = ia;

and expression std::end( ia ) is equivalent to ia + 3

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335