使用 std::累加来查找数组的总和
Using std::accumulate to find sum of array
这是我的数组:
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'))
这是可以理解的,因为mark
和mark.size()
有不同的类型,但我不明白如何以其他方式制作它。我应该铸造他们的类型吗?但是为什么它不是自动制作的呢?array
和&array[0]
相似吗?因为这是我std::accumulate
所需要的.
与内置的 C 样式数组不同,std::array
不会自动衰减到指向其第一个元素的指针。使用std::begin
和std::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()
.
相关文章:
- 在数组中查找总计
- 在二维数组中查找最小值和最大值?
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 查找自动生成键并具有线性内存消耗的小型关联数组
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 如何使用数组查找标准偏差
- 从列表到数组C 查找模式或最常见的数字
- 12个元素的数组 - 查找计数实践
- 使用数组查找HCF,获取未知输出(C )
- C++constexpr数组查找:内存开销?其他问题
- C++字符数组查找/替换字符
- 动态数组查找能力
- 用.用数组查找.C++
- 使用数组查找最大值
- 字典查找与数组查找;数组分配与字典分配
- 使用数组查找最接近的数字C++,浮点
- 定义一个非常大的数组(查找表)的最佳方式是什么
- Std::数组查找最大值函数
- Python在简单数组查找上的小循环的性能问题