不同变量类型的类对象的C++动态数组

问题描述 投票:0回答:1

我正在尝试编写一个动态数组,该数组允许我通过函数 addVehicle 输入唯一数量的车辆,但我在如何使用该数组并向其添加项目方面遇到困难。

我读到动态数组是通过使用向量函数创建的,但我对它的工作原理有点困惑,另外你可以看到我的车辆类别有不同的变量类型,这会干扰吗?

#include <iostream>
#include <vector>

//Silo Storage System

class Silo {
    public:
        std::string name;
        int currentVolume;
        int storageVolume;
};

class Vehicle {
    public:
        std::string model;
        int capacity;
};


void addVehicle(std::vector<vehicle>& vehicle){
    vehicle v;

    
    //std::cout << "Please specify number of vehicles to add" << endl;
    
    std::cout << "Please specify the vehicle model" << std::endl;
    std::cin >> v.model;
    std::cout << "Please specify the load capacity" << std::endl;
    std::cin >> v.capacity;
    
    vehicle.push_back(v);
};


int main() {
    
    Silo depoSilos[3] = {
    {"Silo 1 - Aggregate", 1400,  40000},
    {"Silo 2 - Aggregate", 2300,  20000},
    {"Silo 3 - Aggregate", 11000,  40000}
    };
    
    std::cout << "No. of available silos: " << *(&depoSilos + 1) - depoSilos << std::endl;
    for (int i = 0;i < *(&depoSilos + 1) - depoSilos; i++) {
        std::cout << depoSilos[i].name << " is " << static_cast<double>(depoSilos[i].currentVolume) / static_cast<double>(depoSilos[i].storageVolume) * 100 <<
        "% full." << " Max capacity: " << depoSilos[i].storageVolume << std::endl;
    };

    std::vector<Vehicle> vehicles;
    addVehicle(vehicles);
    
    return 0;
}
c++ dynamic-arrays
1个回答
0
投票

要实现这一目标,您需要:

  1. 提示用户要创建的车辆数量
  2. 用它来准备你的载体
  3. 循环提示用户提供车辆详细信息

它可能是这样的:

void addVehicle(std::vector<vehicle>& vehicles){
    int vehiclesCount = 0;
    
    std::cout << "Please specify number of vehicles to add" << endl;
    std::cin >> vehiclesCount;

    // or some other validation logic for the vehiclesCount
    if (vehiclesCount <= 0) {
      return;
    }

    // pre-allocate memory all at once (only done if necessary)
    vehicles.reserve(vehiclesCount);

    for (int i = 0; i < vehiclesCount; ++i) {
      vehicle v;
      std::cout << "Please specify the vehicle model" << std::endl;
      std::cin >> v.model;
      std::cout << "Please specify the load capacity" << std::endl;
      std::cin >> v.capacity;
    
      vehicle.push_back(v);
    }
}

然后,您可能还想将仅包含

class
成员的
public
转换为
struct
,这将允许它们成为聚合,并因此进行区分。

© www.soinside.com 2019 - 2024. All rights reserved.