【问题标题】:Difference between std::array begin() and data()std::array begin() 和 data() 之间的区别
【发布时间】:2020-04-17 10:51:30
【问题描述】:

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

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

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

【问题讨论】:

    标签: c++ arrays iterator


    【解决方案1】:

    它们在概念上并不相同。

    std::array::begin 返回的是一个iterator,其类型是实现定义的;它可以是 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
    

    【讨论】:

      【解决方案2】:

      实际上两者都不相同。 std::array::data 返回类型是 value_typestd::array::begin 返回类型是 iterator

      std::array::begin 返回指向第一个元素的迭代器,但 std::array::data 返回指向数组对象中第一个元素的指针。

      iteratorrandom access iterator 类型,并且有一个实现,value_type 在数组中定义为其第一个模板参数 (T) 的别名。

      【讨论】:

        猜你喜欢
        • 2014-12-05
        • 1970-01-01
        • 2016-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-22
        • 2018-08-30
        • 1970-01-01
        相关资源
        最近更新 更多