RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: Intermediate
Oct 18, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Treating a Vector As an Array

In certain contexts, you have to treat a vector as an array of its elements. For example, suppose you have a function that takes int * as its argument. How can you pass a vector of int's as an argument to this function? The simplest solution is to take the address of the value returned by front() or operator[]. Because both these member functions return a reference to the internal array of elements, you can use this address as the beginning of an array. For example:

void func(const int arr[], size_t length );
int main()
 vector < int > vi;
 //.. fill vi
 func(&vi[0], vi.size());

vi[0] is the first element of the vector's internal array. You can treat the address of this expression as an array of int's under two conditions: func() doesn't access out-of-range array elements, and the elements inside the vector must be stored in contiguous memory. Although the C++ Standard doesn't guarantee that yet, I'm not aware of any implementation that doesn't use contiguous memory for vectors. Furthermore, this loophole in the C++ Standard is about to be fixed within weeks; the Standard will soon guarantee that vectors use contiguous memory. Therefore, this technique of transforming a vector to a bare array is safe and portable.

Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date