假设我拥有一家维修店,每次新客户来到我的店铺时,我都希望在我的数据库中添加车辆。假设我有一个汽车类,要求提供所有必要的信息。是否可以创建此对象的动态数组,不断增加或减少进入商店的客户车数量,或者这是不可能的?
实施例
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++;
}
答案 0 :(得分:1)
您可能正在寻找标准模板库中的vector
:
#include <vector>
...
vector<Car> car;
...
if (choice == "yes") {
car.push_back(Car{});
}
您的counter
功能不需要main
变量,因为您可以使用
方法size
,它返回向量内的元素数。
e.g。
car.size();
要删除项目,请使用方法pop_back
或方法erase
e.g。
car.pop_back(); // Remove last element from car vector
car.erase(3); // Remove the 4th element from car vector
答案 1 :(得分:1)
是的,原始动态数组可以实现这一点,但是非常很复杂,因为您必须手动管理内存并处理大量指针算法。为了简化此过程,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
的{{1}}。
答案 2 :(得分:1)
让动态分配的数组增长和缩小是可能的,但是很棘手。
幸运的是,标准库为此问题提供了容器(例如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;
}
}