【问题标题】:How to add nested structs to vector [duplicate]如何将嵌套结构添加到向量[重复]
【发布时间】:2015-11-28 18:20:12
【问题描述】:

我正在学习 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。任何帮助将不胜感激。

编辑:一些用户发现此问题与其他用户的其他问题之间存在相似之处。我们实际上正在合作。

【问题讨论】:

  • 实际上,我们正在一起努力,哈哈
  • 你需要在你的Vehicle中创建一个Driver类型的成员变量。
  • 好的,但我真正需要的是将驱动程序添加到 std::find 找到的车辆结构中
  • 很好,一遍又一遍地创建相同的线程,很快你就有了一个mmorpg

标签: c++ vector struct nested


【解决方案1】:

您需要在您的 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"; 
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-24
      • 2012-04-27
      • 2022-08-13
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多