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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: