Martian
Martian

Reputation: 225

Using std::accumulate to find sum of array

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.

Upvotes: 0

Views: 4823

Answers (3)

jrok
jrok

Reputation: 55395

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().

Upvotes: 6

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122457

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().

Upvotes: 0

Roy2511
Roy2511

Reputation: 1038

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

You need to provide iterators to begin and end point.

Upvotes: 0

Related Questions