#include <iostream>
#include <vector>
// 函数声明
int sumGreaterThanThreshold(const std::vector<int>& numbers, int threshold);
int main() {
std::vector<int> numbers = {1, 10, 20, 3, 25};
int threshold = 15;
int result = sumGreaterThanThreshold(numbers, threshold);
std::cout << "大于阈值的数字之和为: " << result << std::endl;
return 0;
}
int sumGreaterThanThreshold(const std::vector<int>& numbers, int threshold) {
int sum = 0;
for (int num : numbers) {
if (num > threshold) {
sum += num;
}
}
return sum;
}
返回普通类型在该场景下的好处
- 简单直接:使用普通的
int
类型返回结果,简单易懂,调用者可以很容易理解返回值的含义,不需要额外的解包或者转换操作。
- 性能高效:普通类型在内存占用和数据传递上相对简单,对于这种简单的求和操作,返回普通类型不会引入额外的性能开销,例如不需要处理复杂的对象构造、析构等操作。
- 兼容性好:普通类型与C++ 其他部分以及其他编程语言的交互性更好。如果该模块需要与其他语言编写的代码集成,普通类型更容易被其他语言识别和处理。