简体   繁体   English

我可以使用不同类型的二维数组吗?

[英]Can I have a two dimensional array of different types?

// create array
Date** dateList = new Date*[SIZE];

// populate array
for(int i = 0; i < SIZE; i++) {
    dateList[i] = new Date[2];
    Date date;
    date.input();

    dateList[i][0] = date;

    int n = dateNum(date);
    dateList[i][1] = n;
}

I want to store a object of Date type in dateList[i][0] and an int in dateList[i][1] . 我想将Date类型的对象存储在dateList[i][0] ,将intdateList[i][1] Is this possible? 这可能吗?

Thank you. 谢谢。

No. 没有。

A single array must be of a single type. 单个数组必须是单个类型。 If you want the elements to represent different types of data, then the element in the array needs to be some kind of base class (pointer), or possibly a discriminated type like a variant . 如果要让元素表示不同类型的数据,则数组中的元素必须是某种基类(指针),或者可能是诸如variant的可区分类型。

Unless you have an overwhelming reason to do otherwise, it sounds like you want a vector of structs: 除非您有绝对的理由要这样做,否则听起来好像您想要一个结构向量:

struct whatever { 
    Date date;
    int n;

    whatever(Date const &d, int i) : date(d), n(i) {}    
};

std::vector<whatever> dates;

Date date;
date.input();

dates.push_back(whatever(date, datenum(date));

There are multiple ways of doing it. 有多种实现方法。 The most direct one is to use union s: put the types that you want to share in a single union , then use the member corresponding to the dimension's type in your code. 最直接的方法是使用union :将要共享的类型放在单个union ,然后在代码中使用与维的类型相对应的成员。 However, this approach is also the most restrictive, because types with constructors / destructors cannot go into union s. 但是,此方法也是限制性最强的,因为带有构造函数/析构函数的类型不能加入union

A more convenient way to do this is to build a one-dimensional array of pair<Date,int> objects, like this: 一种更方便的方法是构建pair<Date,int>对象的pair<Date,int>维数组,如下所示:

pair<Date,int>* dateList = new  pair<Date,int>[SIZE];

// populate array
for(int i = 0; i < SIZE; i++) {
    Date date;
    date.input();
    int n = dateNum(date);

    dateList[i] = make_pair(date, n);
}
for(int i = 0; i < SIZE; i++) {
    cout << "Date: " date[i].first << " ";
    cout << "Int: " date[i].second << endl;
}

This approach lets the compiler check your types much closer, giving you a more robust solution. 这种方法使编译器可以更仔细地检查您的类型,从而为您提供更强大的解决方案。

Short answer: No. Arrays are of one type only. 简短答案:否。数组仅是一种类型。 That is also true for multidimensional arrays. 对于多维数组也是如此。

Read about structs or even higher data structures like map to achieve the dessired effect. 阅读有关结构或什至更高的数据结构(如map以达到所需的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM