【问题标题】:How to print nested struct objects from vector?如何从向量打印嵌套的结构对象?
【发布时间】:2015-11-13 12:40:57
【问题描述】:

我正在开发一个保存车辆库存的程序,因此我为它创建了一个结构。它还需要保留驱动程序列表,因此我为此创建了一个嵌套结构。代码如下:

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;
    }
}
}

但它只打印出第一个结构的元素,打印出驱动程序信息应该在的随机数。你能告诉我我的错误在哪里吗?除嵌套结构外,其他所有内容都可以正常打印。

【问题讨论】:

    标签: c++ vector struct nested


    【解决方案1】:
    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);
    };
    

    【讨论】:

    • 哇,谢谢,没有意识到我的错误。现在,有没有办法只打印向量的一个对象?比如,程序要求输入车牌号,然后打印出其余信息?
    • @DaveCarballo 您可以使用std::find_if 从向量中查找元素。
    猜你喜欢
    • 1970-01-01
    • 2020-11-15
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 2021-03-07
    相关资源
    最近更新 更多