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

5
  • What would you want to do with that pointer? i.e., in what context would it be useful to have a pointer that might be pointing at a std::vector<std::vector<int> > or a std::vector<std::vector<double> >? Commented Jan 18, 2012 at 15:55
  • Do you mean a pointer that could point to either of them? Commented Jan 18, 2012 at 15:58
  • then make a wrapper object to contain double or int. like this: vector<vector<IntOrDouble>> *p Commented Jan 18, 2012 at 16:04
  • How would you use such a pointer? Can you show an example? Commented Jan 18, 2012 at 16:05
  • For what purpose do you plan to use such a pointer? Commented Jan 18, 2012 at 16:05

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

are they any contraindication for the use of that ?
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.
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>

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.