MST

星途 面试题库

面试题:C++中函数返回普通类型在数据处理模块的应用场景示例

假设你正在开发一个数据处理模块,需要统计一组整数中大于某个阈值的数字之和。请使用C++ 编写一个函数,返回这个和(普通类型),并简要说明这种返回普通类型在该场景下的好处。
39.6万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#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;
}

返回普通类型在该场景下的好处

  1. 简单直接:使用普通的int类型返回结果,简单易懂,调用者可以很容易理解返回值的含义,不需要额外的解包或者转换操作。
  2. 性能高效:普通类型在内存占用和数据传递上相对简单,对于这种简单的求和操作,返回普通类型不会引入额外的性能开销,例如不需要处理复杂的对象构造、析构等操作。
  3. 兼容性好:普通类型与C++ 其他部分以及其他编程语言的交互性更好。如果该模块需要与其他语言编写的代码集成,普通类型更容易被其他语言识别和处理。