Current location: Hot Scripts Forums » Programming Languages » C/C++ » C++ Tip : Treating a Vector as an Array


C++ Tip : Treating a Vector as an Array

Reply
  #1 (permalink)  
Old 07-22-10, 01:38 AM
Learnbyexamples Learnbyexamples is offline
Disabled
 
Join Date: Jun 2010
Posts: 8
Thanks: 0
Thanked 0 Times in 0 Posts
C++ Tip : Treating a Vector as an Array

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:
Code:
void func(const int arr[], size_t length );  
int main()  
{  
 vector <int> vi;  
 //.. fill vi  
 func(&vi[0], vi.size());  
}  
</int>
It’s safe to use &vi[0] and &*v.front() as the internal array’s address as long as you adhere to the following rules: First, func() shouldn’t access out-of-range array elements. Second, the elements inside the vector must be contiguous. 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 will be fixed soon.
Reply With Quote
Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Help reading multi-dimensional array l3rady JavaScript 3 06-11-10 04:10 AM
Remove value from array Nikas PHP 1 05-20-09 03:20 AM
Multi-Dimensional Array Help Nikas PHP 17 05-04-09 02:10 AM
Parse error: parse error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ')' Dr. Forensics PHP 3 07-15-06 03:54 PM
linking to iframe not working :( j0d JavaScript 5 01-19-04 08:14 PM


All times are GMT -5. The time now is 01:16 PM.
vBulletin® Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.