[英]C++ pass empty vector of structs to a function
我正在尝试将一个空的结构向量传递给一个函数,该函数将从文件中读取并返回读取的记录数——它将是一个整数。
我在 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++ 书中的其他地方都有介绍。)
顺便说一句,我怀疑您是否想按值获取该向量。
为什么不在int read_records(vector<player> player_info)
之前放置struct player
定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.