0

Here's my array:

std::array<int, 4> mark;

Here's a function I have:

float getAverage() {
        float sum = 0;
        sum = std::accumulate(mark, mark + mark.size(), 0);
        return sum /= mark.size();
    }

But I get following error:

Invalid operands to binary expression ('std::array<int, markAmount>' and 'std::__1::array::size_type' (aka 'unsigned long'))

Which is understandable, as mark and mark.size() have different types, but I don't understand how to make it in other way. Should I cast their types? But why it's not made automatically? Is array similar to &array[0]? As this is what I need for std::accumulate.

3 Answers 3

6

Unlike the built-in C-style arrays, std::array does not automatically decay to a pointer to its first element. Use std::begin and std::end to get the iterators (raw pointers in this case):

std::accumulate(std::begin(mark), std::end(mark), 0);

or member functions .begin() and .end().

Sign up to request clarification or add additional context in comments.

Comments

0

std::accumulate(mark.begin(), mark.end(), 0);

You need to provide iterators to begin and end point.

Comments

0

std::array is not a c-array, ie it does not decay to a pointer. Thats one reason to use it. std::array has no operator+(size_t) and thats what the error is trying to tell you. If you want to accumulate from begin till end then use begin() and end().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.