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

后端 未结 6 1283
陌清茗
陌清茗 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:22

    One thing I'd like to point out for you is that you really don't have to maintain a separate int* to use in dereferencing the array elements, apart from the whole member thing others have well pointed out.

    Using a more modern approach, the code is both more readable, as well as safer:

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    int main()
    {
        std::array cpp_array{1,3,5,7,9};
    
        // Simple walk the container elements.
        for( auto elem : cpp_array )
            cout << elem << endl;
    
        // Arbitrary element processing on the container.
        std::for_each( begin(cpp_array), end(cpp_array), [](int& elem) {
            elem *= 2;      // double the element.
            cout << elem << endl;
        });
    }
    

    Using the lambda in the second example allows you to conveniently perform arbitrary processing on the elements, if needed. In this example, I'm just showing doubling each element, but you can do something more meaningful within the lambda body instead.

    Hope this makes sense and helps.

提交回复
热议问题