简体   繁体   中英

Pointer of std::vector of std::vector

quick question :

Is it possible to make a pointer that can reference a std::vector<std::vector<int> > or a std::vector<std::vector<double>> ?

Thx

If you must you can use the union construct

union intordouble
{
    int x;
    double d;
};

int main()
{
    vector<intordouble> v;
    return 0;
}

Basically the vector is always of the union intordouble so you have a pointer to it and don't need to differentiate. Please take a look at Is it a good practice to use unions in C++?

If using boost is an option, you could use boost:variant . Technically, it is not a pointer but a type-safe single-item container, but it should be able to get the job done without resorting to the "big guns" way of using void* .

void* could point to either, but must be cast to the correct type before use.

A typed pointer can only point to the specified type, including types that inherit from it. Different specialisations of vector are different types, and do not share a common base class, so no typed pointer can point to both of these.

If this is really the sort of thing you think you need to do, you could look into using a discriminated union such as boost::variant to hold various different pointer types.

<bad_guy_mode>

typedef std::vector<std::vector<int>>* vvi_ptr;
typedef std::vector<std::vector<double>>* vvd_ptr;

union int_or_double_vecs{
  vvi_ptr int_vector;
  vvd_ptr double_vector;
};

(Note that only one member is accessible at a time and it's only the one you set last.)

</bad_guy_mode>

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