vector 求 最大值 最小值 和平均值
时间: 2025-02-19 15:54:37 浏览: 74
### C++ Vector 计算最大值、最小值和平均值
对于给定的 `std::vector<double>` 类型的数据集合,可以利用 `<algorithm>` 和 `<numeric>` 库来高效地计算这些统计量。
#### 函数定义
为了封装这一功能,下面提供了一个名为 `calculateStats` 的函数实现:
```cpp
#include <vector>
#include <numeric> // For accumulate()
#include <algorithm> // For max_element() and min_element()
void calculateStats(const std::vector<double>& data, double& maxVal, double& minVal, double& avg) {
if (data.empty()) { // Check whether the vector is empty.
maxVal = 0;
minVal = 0;
avg = 0;
return;
}
// Calculate sum using accumulate from numeric library.
double sum = std::accumulate(data.begin(), data.end(), 0.0);
// Compute average value based on computed sum.
avg = sum / static_cast<double>(data.size());
// Find maximum element within the range specified by two iterators.
maxVal = *std::max_element(data.begin(), data.end());
// Similarly find minimum element with min_element function.
minVal = *std::min_element(data.begin(), data.end());
}
```
此段代码实现了对输入向量的最大值、最小值以及平均值得到精确计算[^1]。通过调用标准库提供的算法工具简化了操作流程并提高了程序可读性和维护性。
阅读全文
相关推荐


















