c++将结构体的空向量传递给函数

C++ pass empty vector of structs to a function

本文关键字:函数 向量 结构体 c++      更新时间:2023-10-16

我试图将一个空的结构向量传递给一个函数,该函数将从文件中读取,它将返回读取的记录数-它将是一个整数。

我在main中初始化了结构体的向量,当我试图将其传递给函数时,我通常会这样做:

int read_records(vector<player> player_info)

它给了我一个"玩家是未定义"的错误。我已经找到了一种绕过它的方法,正如您将在下面的代码中看到的那样,但是逻辑使我相信应该有一种方法可以传递空向量而不必填充第一个下标。

代码如下。请注意,read函数还没有完成,因为我仍然对结构体的向量感到疑惑。

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;
//function prototypes
int read_records(struct player* player_info);
/*
* Define a struct called player that will consist
* of the variables that are needed to read in each
* record for the players. 2 strings for the first
* and last names and 1 integer to hold the statistics
*/
struct player
{
    string first;
    string last;
    int stats;
};
int main(void)
{
    int sort_by, records_read;
    vector<player> player_info(1);
    player * point = &player_info[0];

    cout << "Welcome to Baseball player statistics program!" << endl;
    cout << "How should the information be sorted?" << endl;
    cout << "Enter 1 for First Name" << endl;
    cout << "Enter 2 for Last Name" << endl;
    cout << "Enter 3 for Points" << endl;
    cout << "Enter your selection: ";
    cin >> sort_by;
    //read the records into the array
    records_read = read_records(point);

    system("Pause");
    return 0;
}
int read_records(struct player* player_info)
{
    //declare the inputstream
    ifstream inputfile;
    //open the file
    inputfile.open("points.txt");
    //handle problem if the file fails to open for reading
    if (inputfile.fail())
    {
        cout << "The player file has failed to open!" << endl;
        exit(EXIT_FAILURE);
    }
    else
    {
        cout << "The player file has been read successfully!" << endl;
    }
    return 5;
}

在尝试声明需要知道该类型的函数之前定义类型player

struct player
{
    string first;
    string last;
    int stats;
};
int read_records(vector<player> player_info);

您的解决方案是成功的,因为在struct player*中命名player作为[forward]声明,而在vector<player>中命名它却没有。(这个问题的原因和原因对于这个答案来说太宽泛了,在SO的其他地方和你的c++书中都有涉及。)

作为题外话,我怀疑你是否想要按值取那个向量

为什么不把struct player的定义放在int read_records(vector<player> player_info)的前面呢?