std::array begin() 和 data() 的区别

Waq*_*med 1 c++ arrays iterator

之间有什么区别std::array方法begin()data()?例如:

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

它们可以根据类型而不同吗?或者也许没有区别,这些方法只是为了匹配其他 C++ 数据结构。

son*_*yao 5

它们在概念上并不相同。

什么std::array::begin返回是一个迭代器,其类型是实现定义; 它可以是作为std::array::data返回的指针(指针满足迭代器的要求),但不一定是。

这段代码编译与否取决于实现,例如,这段代码不会用MSVC编译,而是用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
Run Code Online (Sandbox Code Playgroud)