Click here to Skip to main content
15,791,050 members
Articles / General Programming

C++ Tip : Treating a Vector as an Array

Rate me:
Please Sign up or sign in to vote.
4.25/5 (3 votes)
9 Aug 2010CPOL 22K   4   3
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.


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

Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

Generalif you see internal implementation of STL::VECTOR, vector im... Pin
ThatsAlok9-Aug-10 18:35
ThatsAlok9-Aug-10 18:35 
GeneralC++03 tightened up the wording to make vectors contiguous. W... Pin
Aescleal26-Jul-10 3:41
Aescleal26-Jul-10 3:41 
GeneralYou are correct that C++ vector DOESN'T have to be continuou... Pin
Goran Mitrovic23-Jul-10 12:07
Goran Mitrovic23-Jul-10 12:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.