c++将结构体的空向量传递给函数
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++书中都有涉及。)
作为题外话,我怀疑你是否想要按值取那个向量
为什么不把struct player
的定义放在int read_records(vector<player> player_info)
的前面呢?
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 如何使用向量的template_back函数
- 如何通过派生类函数更改基类中的向量
- 变量没有改变?通过向量的函数调用
- 一对向量构造函数:初始值设定项列表与显式构造
- 在c++中使用向量时,如何调用构造函数和析构函数
- std::sort()函数无法对向量的一部分进行排序
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- C++中函数的向量返回类型引发错误
- 添加存储在向量中的大整数的函数出现问题
- 如何在 c++ 中定义接受不同参数类型的函数向量?
- 具有 lambda 函数的函数向量
- 你能用参数制作函数向量吗?
- 在C++中使用成员函数向量时,有没有办法实现协变返回类型
- 在编写 lambda 函数向量时出现隔离错误
- 如何在 boost.process 间共享内存中使用复杂结构"push_back"函数向量
- 是否将std矢量重新分配到默认的构造函数向量是擦除的好方法
- 运行提升for_each中的成员函数向量
- 创建和回推函数向量
- C++,指向函数向量的指针的STL映射