如何从矢量打印嵌套结构对象
How to print nested struct objects from vector?
我正在开发一个保存车辆库存的程序,所以我为它创建了一个结构。它还需要保存驱动程序的列表,所以我为此创建了嵌套结构。这是代码:
struct Vehicle{
string License;
string Place;
int Capacity;
struct Driver{
string Name;
int Code;
int Id;
}dude;
};
我请求用户输入,然后使用以下函数将结构放入向量中:
void AddVehicle(vector<Vehicle> &vtnewV){
Vehicle newV;
Vehicle::Driver dude;
cout << "Enter license plate number: " << endl;
cin >> newV.License;
cout << "Enter the vehicle's ubication: " << endl;
cin >> newV.Place;
cout << "Enter the vehicle's capacity: " << endl;
cin >> newV.Capacity;
cout << "Enter the driver's name: " << endl;
cin >> dude.Name;
cout << "Enter the driver's code: " << endl;
cin >> dude.Code;
cout << "Enter the driver's identification number: " << endl;
cin >> dude.Id;
vtnewV.push_back(newV);
};
现在,我需要的是打印向量内部的结构。我做了以下功能:
void PrintVehicle(vector<Vehicle> vtnewV){
{
vector<Vehicle> ::iterator i;
for (i = vtnewV.begin(); i != vtnewV.end(); i++)
{
cout << "License plate: " << i->License << endl;
cout << "Ubication: " << i->Place << endl;
cout << "Capacity: " << i->Capacity << endl;
cout << "Driver's name: " << i->dude.Name << endl;
cout << "Driver's code: " << i->dude.Code << endl;
cout << "Id: " << i->dude.Id << endl;
cout << " " << endl;
}
}
}
但它只打印出第一个结构的元素,在驱动程序信息应该在的地方打印出随机数。你能告诉我我错在哪里吗?除嵌套结构外,其他所有内容都打印良好。
Vehicle::Driver dude;
您在这里声明了另一个变量,它与newV
(Vehicle
(中的dude
无关。
将代码更改为:
void AddVehicle(vector<Vehicle> &vtnewV){
Vehicle newV;
//Vehicle::Driver dude; // delete it here
cout << "Enter license plate number: " << endl;
cin >> newV.License;
cout << "Enter the vehicle's ubication: " << endl;
cin >> newV.Place;
cout << "Enter the vehicle's capacity: " << endl;
cin >> newV.Capacity;
cout << "Enter the driver's name: " << endl;
cin >> newV.dude.Name;
cout << "Enter the driver's code: " << endl;
cin >> newV.dude.Code;
cout << "Enter the driver's identification number: " << endl;
cin >> newV.dude.Id;
vtnewV.push_back(newV);
};
相关文章:
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 用C#中的并集模拟C++嵌套结构
- 如何在 C++11 中查找和更新向量中的一个嵌套结构
- Lambda 捕获、初始值设定项和嵌套结构
- 使用g++静态初始化带有命名标签的嵌套C++结构
- 重载嵌套结构/类的流插入运算符
- C++将结构传递给函数以访问嵌套结构
- C++ 在外部使用嵌套结构实现类函数
- 嵌套结构,从由空行分隔的文件中读取数据
- 在 glsl opengl 中将嵌套结构数组作为统一传递
- 受保护的嵌套结构不能用作派生外部类中的返回类型?
- C++中的嵌套结构
- 使用嵌套结构初始化并集
- C++ 中的嵌套结构函数
- C++中匿名类型的嵌套结构
- c++ 嵌套结构映射找不到成员
- C 嵌套结构上的 g++ 编译错误
- 不能使用嵌套结构中的联合元素作为 scanf() 的参数来存储所需的值
- 如何将值添加到嵌套结构中,该结构在C++中有两个指针