使用 std::累加来查找数组的总和

Using std::accumulate to find sum of array

本文关键字:数组 查找 std 使用      更新时间:2023-10-16

这是我的数组:

std::array<int, 4> mark;

这是我有一个功能:

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

但是我收到以下错误:

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

这是可以理解的,因为markmark.size()有不同的类型,但我不明白如何以其他方式制作它。我应该铸造他们的类型吗?但是为什么它不是自动制作的呢?array&array[0]相似吗?因为这是我std::accumulate所需要的.

与内置的 C 样式数组不同,std::array不会自动衰减到指向其第一个元素的指针。使用std::beginstd::end获取迭代器(在本例中为原始指针(:

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

或成员函数.begin().end()

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

您需要提供迭代器来开始和结束点。

std::array

不是c数组,即它不会衰减到指针。这是使用它的原因之一。std::array没有operator+(size_t),这就是错误试图告诉您的。如果您想从头到尾累积,请使用begin()end().