Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming

C++ Tip : Treating a Vector as an Array

4.25/5 (3 votes)
9 Aug 2010CPOL 23.9K  
Suppose you have a vector of int and function that takes int *. To obtain the address of the internal array of the vector v and pass it to the function, use the expressions &v[0] or &*v.front().


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

It is safe to use &vi[0] and &*v.front() as the internal array’s address as long as you adhere to the following rules:

  • func() shouldnot access out-of-range array elements.
  • the elements inside the vector must be contiguous. Although the C++ Standard doesnot guarantee that yet

However,I amn't aware of any implementation that doesn’t use contiguous memory for vectors. Furthermore, this loophole in the C++ Standard will be fixed soon.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)