我正在学习C ++,我必须创建一个程序来跟踪车辆及其驱动程序。我正在使用结构和向量来实现这一点。这是结构和向量的声明:
struct Vehicle {
string License;
string Place;
int Capacity;
struct Driver {
string Name;
int Code;
int Id;
};
};
vector<Vehicle> &vtnewV
好的,程序然后要求用户输入以获取基本信息,我使用以下函数:
void AddVehicle() {
Vehicle newV;
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;
vtnewV.push_back(newV);
然后我需要输入以获取有关驱动程序的信息。我不知道怎么做。以下是我到目前为止编写的内容:
void AddDriver(){
int Plate;
string DriverName;
int Code;
int Id;
system("CLS");
cout << "Enter the vehicle's license plate number: " << endl;
cin >> Plate;
if(std::find(vtnewV.begin(), vtnewV.end(), Plate) != vtnewV.end())
system("CLS");
cout << "Enter the driver's name: " << endl;
cin >> DriverName;
cout << "Enter the driver's code: " << endl;
cin >> Code;
cout << "Enter the driver's id: " << endl;
cin >> Id;
Vehicle::Driver fella;
fella.Name = DriverName;
fella.Code = Code;
fella.Id = Id;
}
事情是,我不知道如何“选择”它找到的结构,然后将Driver结构添加到Vehicle。任何帮助将不胜感激。
编辑:有些用户发现此问题与其他用户之间存在相似之处。我们实际上在一起工作。答案 0 :(得分:4)
您需要在Vehicle中创建一个类型为Driver的成员变量。
例如:
struct Vehicle {
// This is just a type, not an object
struct Driver {
string Name;
int Code;
int Id;
};
string License; // This is an object of type std::string
string Place;
int Capacity; // This is an object of type int
Driver driver; // THIS is an object of type Driver
};
int main()
{
Vehicle vehicle;
// now we can refer to the object of type Driver
// that we appropriately named "driver"
vehicle.driver.Name = "Bob";
}
答案 1 :(得分:0)
将Driver
类型的成员添加到您的结构
struct Vehicle {
string License;
string Place;
int Capacity;
struct Driver {
string Name;
int Code;
int Id;
} driver; // driver is a member of Vehicle and of type Driver
};