c++ - 具有不同元素的数组c++

标签 c++ arrays

我需要将节目中的一些数据放入一个数组中。

我有这个功能:

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 个显示。

我可以做一个二维动态数组来解决这个问题吗?

最佳答案

您需要创建代表节目的structureclass。这并不难:

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/

相关文章:

c++ - STL 的段错误,如 skiplist 实现

c++ - 如何避免使用 R 值的悬空引用

c - 在 C 语言中,为什么数组的地址等于它的值?

Javascript迭代高亮

java - int 数据类型初始化 : Array vs Regular

c++ - GCC C++ (ARM) 和指向结构字段的常量指针

c++ - 错误 LNK2019 : unresolved external symbol ___iob_func referenced in function "void __cdecl Padding(int)"

c++ - 计算递归和时无限循环

java - 如何在不使用集合的情况下从 Java 中的给定数组中删除重复元素

asp.net - jQuery 中数组长度为零