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

Ale*_*Top 1 c++ vector

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

我在main中初始化结构向量,当我尝试将它传递给函数时,我会定期执行它:

int read_records(vector<player> player_info)
Run Code Online (Sandbox Code Playgroud)

它给了我一个"玩家未定义"的错误.我已经找到了一种绕过它的方法,你将在下面的代码中看到,但是逻辑让我相信应该有一种方法来传递空向量而不必填写第一个下标.

代码如下.请注意,读取功能尚未完成,因为我仍然想知道结构的向量.

#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;

}
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 5

player 尝试声明需要了解该类型的函数之前定义类型.

struct player
{
    string first;
    string last;
    int stats;
};

int read_records(vector<player> player_info);
Run Code Online (Sandbox Code Playgroud)

你的解决方法是成功的,因为命名playerstruct player*充当[转发]声明,因为在它的命名方式vector<player>没有.(这个问题的原因和原因对于这个答案而言过于宽泛,并且在SO和C++书籍的其他地方都有涉及.)

顺便说一句,我怀疑你想要按值获取该向量.