0

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

parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85
Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134

4 Answers4

2

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

Community
  • 1
  • 1
parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85
  • are they any contraindication for the use of that ? – Matthieu Riegler Jan 18 '12 at 16:09
  • 1
    You can't use that union without some way of knowing which type is currently in it. If all the elements in any vector will be the same type, then you can add an extra data member to the vector to indicate which type it contains. If you want to store heterogeneous elements within a single array, then you'll need to use (or reinvent) `boost::variant`. – Mike Seymour Jan 18 '12 at 16:38
2

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

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

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

Xeo
  • 129,499
  • 52
  • 291
  • 397