Reputation: 3810
I understand "How to convert vector to array in C++"
answers how to convert a vector of doubles (NON POINTER TYPE) to an array.
My requirement :: To convert (a vector of CustomClass pointers) to (a CustomClass pointer to an array of CustomClass pointers).
Does the following code mean "(vector of pointers) --> (Pointer to an array of CustomClass pointers)"
std::vector <CustomClass*> vectorObject(SizeOfVector); // Here each element of the vector //is a pointer to CustomClass object.
CustomClass* customClassArray = &vectorObject[0];
Please correct me if I am wrong. Kindly Help with a code snippet.
Thanks in advance.
Upvotes: 1
Views: 2345
Reputation: 67382
Actually vectorObject[0]
is a CustomClass *
, so &vectorObject[0]
is a CustomClass **
.
You're making an interesting assumption here, that vector<>
stores its elements sequentially. You're probably right though, so your code should work.
Edit: As per Ben Voigt's comments, the contiguousness of vector<>
is guaranteed by the standard, so this method will 100% work.
Upvotes: 2
Reputation: 25495
Vector is a wrapper in a sorts for an array and provides all the features of an array whilst also allowing the array to grow shrink know how big it is and a lot of other useful features. One of the requirements of std vector is that its data is stored in a contiguous fashion like an array. Because of this requirement you can get an array of elements by taking the address of the first element regardless of type.
std::vector <CustomClass*>vectorObject
Means that you have a vector of CustomClass Pointers to get an array
CustomClass **Array = &vectorObject[0]
Now I have taken the contiguous data segment at offset 0 in the vector and assigned it the a pointer pointer of customclass remember that arrays and pointers are deeply connected in c and c++ I can now access the pointer pointer as if it were an array
CustomClass * FirstEle = Array[0];
Upvotes: 2
Reputation: 7136
Yes, vectors are required to be consequtive in memory, so the expression "&vectorObject[0]" would return the address of the first element, in which you can point to.
Upvotes: 2