我需要将节目中的一些数据放入一个数组中。
我有这个功能:
addShow(string name, string theatre, string day, string hour, int totalTickets, float price)
我有一个动态数组,其最大长度是可以完成的最大显示。
arrayShows = new int[totalShows];
现在,我需要将每个节目的数据放入这个数组中,我该怎么做?
我是这样想的:
count = 0;
arrayShows[count]= name;
arrayShows[count+1]= theatre;
arrayShows[count+2]= day;
arrayShows[count+3]= hour;
arrayShows[count+4]= totalTickets;
arrayShows[count+5]= price;
count += 6;
但是如您所见,如果最大显示是 5 个,这是不正确的,因为我只能放入第一个显示的一些数据,而不会存储其他 4 个显示。
我可以做一个二维动态数组来解决这个问题吗?
最佳答案
您需要创建代表节目的structure
或class
。这并不难:
struct Show {
Show() = default;
Show(const std::string& name, const std::string& theater,
const std::string& day, const std::string& hour,
int totalTickets, float price)
: name(name)
, theater(theater)
, day(day)
, hour(hour)
, totalTickets(totalTickets)
, price(price)
{}
std::string name;
std::string theater;
std::string day;
std::string hour;
int totalTickets;
float price;
};
然后,避免使用动态数组并使用 std::vector
相反:
std::vector<Show> shows(totalShows);
shows[0] = Show(name, theater, day, hour, totalTickets, price);
或者直接添加新元素:
shows.emplace_back(name, theater, day, hour, totalTickets, price);
当然,还有其他方法,例如使用 std::tuple
,但您不需要让事情变得比现在更复杂。
关于c++ - 具有不同元素的数组c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47368641/