尝试将向量或数组调用到另一个函数中

问题描述 投票:0回答:1

我一直在学习向量和数组,但我猜我错过了一些东西。对于分配,我需要对程序进行调制并调用主程序,但我正在努力寻找如何将向量/数组数据携带到其他要使用的函数中的答案。

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

int getData() {
    int size = 16;
    vector<int> weeklyScore(16, 0);  // initialize
    for (int counter = 0; counter < 16; counter++) {
        cout << "Enter quiz score (0-15) for week " << counter + 1 << " : "
             << endl;
        cin >> weeklyScore.at(counter);  // fill with data
        if (weeklyScore.at(counter) < 0 || weeklyScore.at(counter) > 15) {
            cout << "Please enter a valid score (0-15): " << endl;
            counter--;
        }
    }
    for (int i = 0; i < size; i++) {
        cout << weeklyScore.at(i) << endl;
    }
    return weeklyScore;  // error here
}

int highScore() {  // new function
    int high;
    int i;
    for (i = 0; i < 16; i++) high = 0;
    if (weeklyScore.at(i) > high) {  // use of vector
        high = i;
    }
    cout << "The highest score is: " << high << endl;
    return 0;
}

此时我从第 28 行收到错误:

return weeklyScore;
no viable conversion from returned value of type 'vector<int>' to function return type 'int'
c++ vector modularity
1个回答
0
投票

首先,修复返回类型以匹配返回的值。

vector<int> getData() {
    // ...
}

然后调用该函数并将值存储在

highScore
函数中的变量中。

int highScore() {
    auto weeklyScore = getData();
    // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.