Matthieu Riegler
Matthieu Riegler

Reputation: 54998

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

Upvotes: 0

Views: 306

Answers (4)

Mike Seymour
Mike Seymour

Reputation: 254471

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.

Upvotes: 1

Xeo
Xeo

Reputation: 131799

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

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

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

Upvotes: 2

parapura rajkumar
parapura rajkumar

Reputation: 24403

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++?

Upvotes: 2

Related Questions