我需要在show中输入一些数据。
我有这个功能:
addShow(string name, string theatre, string day, string hour, int totalTickets, float price)
我有一个dinamic数组,最大长度是可以完成的最大显示。
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个节目将不会被存储。
我可以用二维dinamic数组来解决这个问题吗?
答案 0 :(得分:2)
您需要创建代表节目的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
,但你不需要让事情变得更复杂。
答案 1 :(得分:0)
如果要在数组中存储不同类型,可以使用C ++ 17 std::any
或std::variant
。
std::any
:
std::vector<std::any> arrayShows;
arrayShows.push_back(name);
arrayShows.push_back(theatre);
arrayShows.push_back(day);
arrayShows.push_back(hour);
arrayShows.push_back(totalTickets);
arrayShows.push_back(price);
std::variant
:
std::vector<std::variant<int, float, std::string>> arrayShows;
arrayShows.push_back(name);
arrayShows.push_back(theatre);
arrayShows.push_back(day);
arrayShows.push_back(hour);
arrayShows.push_back(totalTickets);
arrayShows.push_back(price);
或者如果你不能使用C ++ 17,你可以使用type erasure实现自己的解决方案。
答案 2 :(得分:0)
为您的数据创建类,然后创建将要执行的类对象的数组