Reputation: 55
Lets say that I own a repair shop and I want to add a vehicle to my database each time a new customer comes to my shop. Assuming that I have a car class that asks for all the necessary information. Is is possible to create a dynamic array of this object that is constantly adding or subtracting the amount of customer cars that come into the shop, or is this more improbable?
Ex.
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++;
}
Upvotes: 0
Views: 58
Reputation: 128
You may be looking for vector
from the Standard Template Library:
#include <vector>
...
vector<Car> car;
...
if (choice == "yes") {
car.push_back(Car{});
}
You won't need counter
variable on your main
function, since you can use
the method size
, which returns the number of elements inside the vector.
e.g.
car.size();
For removing items, use the method pop_back
or the method erase
e.g.
car.pop_back(); // Remove last element from car vector
car.erase(3); // Remove the 4th element from car vector
Upvotes: 1
Reputation: 11769
Yes, this is possible with raw dynamic arrays, but it is very complicated as you are going to have to manually manage your memory and deal with a lot of pointer arithmetic. To simplify this process, the STL contains std::vector
which represents an dynamic array that can easily be changed in size. For example:
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
}
Similarly, to remove a Car
, you can use std::vector::pop_back
which can be called in the same way as std::vector::push_back
.
Upvotes: 1
Reputation: 35154
Letting a dynamically allocated array grow and shrink is possible, but tricky.
Fortunately, standard library provides containers (e.g. std::vector
) for exactly this issue:
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;
}
}
Upvotes: 1