[英]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.