You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将vector/array传递给其他函数?C++代码报错求助

问题解决:vector返回值错误与数据传递方法

错误原因分析

你遇到的第28行报错,核心原因是函数返回类型不匹配:getData()声明的返回类型是int,但你试图返回一个vector<int>类型的变量,C++不允许这种隐式转换,所以触发报错。

另外highScore()函数存在两个明显问题:

  • 没有接收vector<int>参数,直接使用未定义的weeklyScore变量
  • 找最高分的逻辑错误,循环内的赋值和判断逻辑完全不符合需求

修正后的完整代码

#include <iostream>
#include <string>
#include <vector>
using namespace std;

// 修改返回类型为vector<int>,返回填充好的vector
vector<int> getData() {
    const int size = 16; // 用const固定大小,代码更规范
    vector<int> weeklyScore(size, 0);  // 初始化vector
    for (int counter = 0; counter < size; counter++) {
        cout << "Enter quiz score (0-15) for week " << counter + 1 << " : " << endl;
        cin >> weeklyScore.at(counter);  // 填充数据
        if (weeklyScore.at(counter) < 0 || weeklyScore.at(counter) > 15) {
            cout << "Please enter a valid score (0-15): " << endl;
            counter--; // 重新输入当前周的分数
        }
    }
    // 打印输入的分数(可选)
    cout << "All entered scores:" << endl;
    for (int score : weeklyScore) { // 范围for循环更简洁
        cout << score << endl;
    }
    return weeklyScore;
}

// 接收vector<int>的const引用作为参数,避免拷贝开销且保证数据不被修改
void highScore(const vector<int>& scores) {
    int high = scores[0]; // 用第一个元素初始化最高分
    for (int score : scores) {
        if (score > high) {
            high = score;
        }
    }
    cout << "The highest score is: " << high << endl;
}

// main函数作为程序入口,调用两个函数完成完整流程
int main() {
    vector<int> scoreData = getData();
    highScore(scoreData);
    return 0;
}

正确传递vector/array到其他函数的方法

1. 传递vector的常用方式

  • 值传递:直接传vector<int> scores,会创建vector的副本,开销较大,仅适合小型vector
  • const引用传递:const vector<int>& scores,不会拷贝原数据,且保证函数内无法修改vector,是最常用的传递方式(如上面的highScore函数)
  • 非const引用传递:vector<int>& scores,允许函数修改原vector的数据,适用于需要修改vector内容的场景

2. 传递C-style数组的方式

如果使用的是C语言风格的数组(如int scores[16]),有两种传递方式:

  • 传递数组名+大小:void highScore(const int scores[], int size),注意数组名会退化为指针,必须额外传递数组大小
  • 使用模板函数自动推导大小:
    template <size_t N>
    void highScore(const int (&scores)[N]) {
        // 可以直接用N作为数组大小
    }
    

内容的提问来源于stack exchange,提问作者Islandari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 03:23:31