Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > reserve() in vector?

Reply
Thread Tools

reserve() in vector?

 
 
wenmang@yahoo.com
Guest
Posts: n/a
 
      10-03-2006
hi,
I like to preallocate a vector of an element X, my question is after
calling reserve(), is there a guarantee that memory is contiguous?

 
Reply With Quote
 
 
 
 
Victor Bazarov
Guest
Posts: n/a
 
      10-03-2006
http://www.velocityreviews.com/forums/(E-Mail Removed) wrote:
> I like to preallocate a vector of an element X, my question is after
> calling reserve(), is there a guarantee that memory is contiguous?


Yes.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask


 
Reply With Quote
 
 
 
 
red floyd
Guest
Posts: n/a
 
      10-03-2006
Victor Bazarov wrote:
> (E-Mail Removed) wrote:
>> I like to preallocate a vector of an element X, my question is after
>> calling reserve(), is there a guarantee that memory is contiguous?

>
> Yes.


Specifically 23.2.4/1 (ISO/IEC 14882:2003).

"The elements of a vector are stored contiguously, meaning that if v is
a vector<T, Allocator> where T is some type other than bool, then it
obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size()."
 
Reply With Quote
 
Alan Johnson
Guest
Posts: n/a
 
      10-04-2006
(E-Mail Removed) wrote:
> hi,
> I like to preallocate a vector of an element X, my question is after
> calling reserve(), is there a guarantee that memory is contiguous?


As others have said, the memory is guaranteed to be contiguous.
However, from the wording of your question it sounds like you may
misinterpret the intent of the reserve function. Are you trying to do
something like this?

void some_library_function(char * p, size_t len)
{
// Write to p.
}

int main()
{
std::vector<char> v ;
v.reserve(100) ;
some_library_function(&v[0], 100) ; // ERROR!!
}

Calling reserve will allocate enough memory to hold the specified
number of objects, but it doesn't give you access to that memory. That
is, after a call to reserve, the vector still contains the same number
of elements as before to call to reserve. If your intent is to do
something like the above, use resize instead of reserve.

--
Alan Johnson

 
Reply With Quote
 
 
 
Reply

Thread Tools

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 On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off




Advertisments