改变动态数组的长度?

Changing Dynamic Arrays lengths?

假设我拥有一家维修店,每次有新客户光顾我的店时,我都想将一辆车添加到我的数据库中。假设我有一辆车 class 需要所有必要的信息。是否可以创建此对象的动态数组,不断增加或减少进入商店的客户汽车数量,或者这更不可能?

例如

    using namespace std; //I know its not a good idea to use, prof wants us too.

    class Car{
         Car(){
         //get user data
         }
    };

    int main () {

          int choice;
          static int counter = 0;
          Car *car = new Car[Counter];

          cout << "Would you like to add a vehicle to the our database(yes/no): ";
          cin >> choice;
                if (choice == "yes") {
                    car[counter].Car::Car();
                    counter++;
                }   

您可能正在从 标准模板库 中查找 vector

#include <vector>

...
vector<Car> car;
...
if (choice == "yes") {
    car.push_back(Car{});
}

您的 main 函数不需要 counter 变量,因为您可以使用 方法 size,其中 returns 向量中的元素数。

例如

car.size();

要删除项目,请使用方法 pop_back 或方法 erase

例如

car.pop_back();  // Remove last element from car vector
car.erase(3); // Remove the 4th element from car vector

是的,这对于原始动态数组是可能的,但它非常复杂,因为您将不得不手动管理内存并处理大量指针运算。为了简化这个过程,STL 包含 std::vector,它表示一个可以轻松更改大小的动态数组。例如:

std::vector<Car> car;

cout << "Would you like to add a vehicle to the our database(yes/no): ";
cin >> choice;

if (choice == "yes") {
    car.push_back(Car{}); // No indices required; Just add a new car to the end
    counter++; // You might not even need this, 
               // as there is std::vector::size for that
}

同样,要删除Car,可以使用std::vector::pop_back,其调用方式与std::vector::push_back相同。

让动态分配的数组增长和收缩是可能的,但很棘手。 幸运的是,标准库为这个问题提供了容器(例如 std::vector):

struct Car{
    Car(string _type) : type(_type) { };
    string type;
};

int main () {

    std::vector<Car> cars;
    while(1) {
        string input;
        cout << "Enter the type of a new car (or 'exit'):" << endl;
        if (!(cin >> input) || input=="exit") {
            break;
        }
        cout << "added." << endl;
        cars.emplace_back(input);
    }

    cout << "you have entered " << cars.size() << " car(s):" << endl;
    for(auto car : cars) {
        cout << car.type << endl;
    }

}