gpt4 book ai didi

c++ - 如何在 C++ 中向 vector 添加新对象

转载 作者:行者123 更新时间:2023-11-30 01:14:37 26 4
gpt4 key购买 nike

我正在尝试创建一个程序,该程序允许用户将名为 Vehicle 的类的对象添加到存储在 vector 中的库存中。 vector 的初始大小为零。每个对象都是用户输入其属性的车辆。

我无法解决的问题是,如果每辆车都需要成为自己独立的对象,如何让用户不断添加车辆。如果用户决定继续向库存中添加更多车辆(对象)(vector 称为 carList),您如何让 C++ 确定新对象的名称。

有人可以指导我正确的方向吗?如果这很明显,我深表歉意,我是这门语言的新手。我必须做一些涉及动态分配对象或类似事情的事情吗?

这是我的(不完整的)代码:

void addVehicle(vector<Vehicle> carList)
{
char stop; // Needed for stopping the do-while loop
string VIN = "", // Needed to hold user input for the VIN
Make = "", // Needed to hold user input for the Make
Model = ""; // Needed to hold user input for the Model
int Year = 0; // Needed to hold user input for the Year
double Price = 0.0; // Needed to hold user input for the Price

cout << "You have chosen to add a vehicle to your inventory.\n\n";

do
{
cout << "There are currently " << carList.size() << " vehicles in your inventory.\n\n"
<< "\t\t\tVehicle #" << (carList.size() + 1) << ": \n"
<< "\t\t___________________________\n\n";

Vehicle /*new object needs to go here*/
carList.push_back(/*new object from the line above*/);

// Prompt user to input VIN
cout << "VIN: ";
cin >> VIN;

// Prompt user to input Make
cout << "Make: ";
cin.ignore();
getline(cin, Make);

// Prompt user to input Model
cout << "Model: ";
getline(cin, Model);

// Prompt user to input Year
cout << "Year: ";
cin >> Year;

// Prompt user to input Price
cout << "Price: $";
cin >> Price;

Call to the overloaded constructor to store user input in object
/*(newly created object)*/.Vehicle::Vehicle(VIN, Make, Model, Year, Price);

// Ask user if they would like to enter another vehicle
cout << "\nWould you like to enter another vehicle? (Y/N):";
cin.ignore();
stop = cin.get();

} while (stop != 'N');

如有任何帮助,我们将不胜感激。谢谢!

最佳答案

如何先创建对象,然后将拷贝推送到 vector 中?

Call to the overloaded constructor to store user input in object
Vehicle temp(VIN, Make, Model, Year, Price);
carList.push_back(temp);

但是实际上不需要变量:

Call to the overloaded constructor to store user input in object
carList.push_back(Vehicle(VIN, Make, Model, Year, Price));

如果你有 C++11,你甚至可以直接就地构建对象:

Call to the overloaded constructor to store user input in object
carList.emplace_back(VIN, Make, Model, Year, Price);

妈妈,没有拷贝!

关于c++ - 如何在 C++ 中向 vector 添加新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29888316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com