Waqar
Waqar

Reputation: 9331

Difference between std::array begin() and data()

What is the difference between std::array method begin() and data()? For example:

std::array<int, 5> = { /* numbers */ };
int* it = array.begin();
int* data = array.data();
// it and data are same here

Can they be different depending upon the type? Or maybe there is no difference and these methods are just there to match other c++ data structures.

Upvotes: 3

Views: 1307

Answers (2)

songyuanyao
songyuanyao

Reputation: 172934

They're not the same, in concept.

What std::array::begin returns is an iterator, whose type is implementation-defined; it could be pointer as std::array::data returns (pointer satisfies the requirement of iterator), but doesn't have to be.

This code compiles or not depends on implementation, for example, this code won't compile with MSVC but compiles with Clang.

Error(s):
source_file.cpp(7): error C2440: 'initializing': cannot convert from 'std::_Array_iterator<_Ty,5>' to 'int *'
        with
        [
            _Ty=int
        ]
source_file.cpp(7): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

Upvotes: 7

Eklavya
Eklavya

Reputation: 18450

Both are not same accually. std::array::data return type is value_type and std::array::begin return type is an iterator.

std::array::begin returns an iterator pointing to the first element but std::array::data returns a pointer to the first element in the array object.

iterator is random access iterator types and there is a implementation for it and value_type defined in array as an alias of its first template parameter (T).

Upvotes: 1

Related Questions