Afonso Matos
Afonso Matos

Reputation: 2476

C++ begin() and end()

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

Upvotes: 2

Views: 1897

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310970

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

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117866

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.

Upvotes: 4

TartanLlama
TartanLlama

Reputation: 65610

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

Upvotes: 11

Related Questions