Reputation: 123
I have a question about converting from std::vector to an array. I have a vector of pointers to object. How can I convert it to an array of pointer to objects in C++?
The vector is
std::vector<pin*> *_PINS
I want to convert it to
pin** pins_arr
I've tried everything that has been suggested in here but it doesn't work
I guess the reason why it's not working is because I have pointer to object as a type instead of basic type.
Would you please help me with this? I've been stucked for the whole morning.
Thank you,
Upvotes: 2
Views: 1261
Reputation: 490018
Edit: if you really insist on doing a conversion like this, I suppose you could do something on this order:
std::vector<PIN *> *_PINS;
_PINS = new std::vector<PIN *>;
// make life a little easier:
std::vector<PIN *> tmp = *_PINS;
PIN *pins = new PIN *[10];
for (int i=0; i<10; i++)
pins[i] = tmp[i];
PIN **ppins = &pins;
I have to agree with Ed.S though -- what you're doing here defeats most of the purpose of using std::vector
in the first place, and frankly strikes me as a bit silly.
Upvotes: 2
Reputation: 60004
the member function data() returns the array, so _PINS->data() should work...
Upvotes: 2
Reputation: 124632
So, first off; why are you using a vector of pointers at all? Why are you storing a pointer to a vector?! This circumvents the vector's ability to manage memory for you and is almost certainly wrong. Let the vector do what it was meant to do, it handles dynamic allocation and clanup for you behind the scenes.
vectors guarantee that their memory is stored in contiguous space, so the address of the first element can be used as a pointer, i.e., an array. When you store a pointer to a vector you once again eliminate it's ability to clean up deterministically based upon scope. The destructor will not run until you manually call delete
on it.
You are essentially using a vector as an array here. Again, this is wrong. The vector itself is a lightweaght object, there is no good reason to dynamically allocate it. Pass a vector&
to functions that need to use it.
However, and more importantly; you are doing it wrong. Just use this:
using std::vector;
//...
vector<pin> pins; // that's it! really!
Upvotes: 1