Cannot use .begin() or .end() on an array

后端 未结 6 1290
陌清茗
陌清茗 2020-12-05 10:01

The error reads:

request for member \'begin\', \'end\' in \'arr\' which is non class type int[5], unable to deduce from expression error.

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 10:29

    Arrays have no member functions as they aren't a class type. This is what the error is saying.

    You can use std::begin(arr) and std::end(arr) from the header instead. This also works with types that do have .begin() and .end() members, via overloading:

    #include 
    #include 
    
    #include 
    
    int main()
    {
        int c_array[5] = {};
        std::array cpp_array = {};
        std::vector cpp_dynarray(5);
    
        auto c_array_begin = std::begin(c_array); // = c_array + 0
        auto c_array_end = std::end(c_array);     // = c_array + 5
    
        auto cpp_array_begin = std::begin(cpp_array); // = cpp_array.begin()
        auto cpp_array_end = std::end(cpp_array);     // = cpp_array.end()
    
        auto cpp_dynarray_begin = std::begin(cpp_dynarray); // = cpp_dynarray.begin()
        auto cpp_dynarray_end = std::end(cpp_dynarray);     // = cpp_dynarray.end()
    }
    

提交回复
热议问题