Click here to Skip to main content
15,389,840 members
Articles / General Programming
Tip/Trick
Posted 23 Jul 2010

Tagged as

Stats

20.5K views
4 bookmarked

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
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)

Share

About the Author

elitehussar
United States United States
No Biography provided

Comments and Discussions

 
Generalif you see internal implementation of STL::VECTOR, vector im... Pin
ThatsAlok9-Aug-10 17:35
MemberThatsAlok9-Aug-10 17:35 
GeneralC++03 tightened up the wording to make vectors contiguous. W... Pin
Aescleal26-Jul-10 2:41
MemberAescleal26-Jul-10 2:41 
GeneralYou are correct that C++ vector DOESN'T have to be continuou... Pin
Goran Mitrovic23-Jul-10 11:07
MemberGoran Mitrovic23-Jul-10 11:07 
GeneralVectors are guaranteed to be continuous: http://www.parashif... Pin
iberg22-Jul-10 2:31
Memberiberg22-Jul-10 2:31 

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.