简体   繁体   中英

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] . 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 .

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. However, this approach is also the most restrictive, because types with constructors / destructors cannot go into union s.

A more convenient way to do this is to build a one-dimensional array of pair<Date,int> objects, like this:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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