Wrox Programmer Forums
Go Back   Wrox Programmer Forums > C# and C > C++ and Visual C++ > C++ Programming
|
C++ Programming General discussions for the C++ language. For questions specific to Microsoft's Visual C++ variant, see the Visual C++ forum instead.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the C++ Programming section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
  #1 (permalink)  
Old July 22nd, 2010, 02:36 AM
EliteHussar
Guest
 
Posts: n/a
Default 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());  
}
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.

Last edited by EliteHussar; July 22nd, 2010 at 02:57 AM..
Reply With Quote





Similar Threads
Thread Thread Starter Forum Replies Last Post
getting a result set to a vector cakalanka Java Databases 1 March 24th, 2008 07:33 AM
Treating Memory as a File BrianWren Pro VB 6 6 July 27th, 2007 01:27 PM
Vector problem ronnie5 C++ Programming 3 November 9th, 2005 08:18 AM
Trouble Using Vector Iain C++ Programming 0 April 7th, 2004 08:12 PM
vector.add(); chikodi Servlets 2 October 23rd, 2003 02:03 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.