473,320 Members | 2,133 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

how does reserve() work?

JDT
Hi,

My understanding about vector's reserve() is to allocate memory for the
vector. If so, is it right that each push_back() in the following loop
causes no memory reallocation and its execution time should be constant
(i.e. internally, only one value is copied and then the integer "size"
is increased by one)? Thanks for any help.

vector<intv;
v.reserve(100);
for (int i=0; i<100; i++)
v.push_back(i);

JD
Apr 13 '07 #1
3 2004
JDT wrote:
My understanding about vector's reserve() is to allocate memory for
the vector. If so, is it right that each push_back() in the
following loop causes no memory reallocation and its execution time
should be constant (i.e. internally, only one value is copied and
then the integer "size" is increased by one)? Thanks for any help.
Yes. The value when it's pushed without reallocation is simply
copy-constructed using "placement new" (in most implementations).

Most implemenations employ some kind of "hidden" reserve() even
though you don't use it directly. They usually allocate more memory
than is immediately needed to prevent frequent reallocations. To
learn the capacity of the vector (how many elements it can contain
before next reallocation), call 'capacity' member function.
vector<intv;
v.reserve(100);
for (int i=0; i<100; i++)
v.push_back(i);
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 13 '07 #2
your understanding is perfect --- as it is the same as one of my c++
books said.

Apr 14 '07 #3
On Apr 14, 1:24 am, JDT <jdt_yo...@yahoo.comwrote:
My understanding about vector's reserve() is to allocate memory for the
vector. If so, is it right that each push_back() in the following loop
causes no memory reallocation and its execution time should be constant
(i.e. internally, only one value is copied and then the integer "size"
is increased by one)? Thanks for any help.
vector<intv;
v.reserve(100);
for (int i=0; i<100; i++)
v.push_back(i);
That's correct. More importantly, it is guaranteed that none of
the push_back's invalidate iterators, references or pointers
into the vector, e.g.:

vector< int v ;
v.push_back( 0 ) ;
vector< int >::iterator i = v.begin() ;
int& r = v[ 0 ] ;
int* p = &v[ 0 ] ;
for ( int i = 1 ; i < 100 ; ++ i ) {
v.push_back( i ) ;
}

With the reserve, i, r and p are guaranteed to still be valid
here. Without the reserve, no.

In most programs, this is by far the real reason to use reserve.
The standard requires amortized constant time for push_back
anyway, so you won't get very many re-allocations, regardless of
what you do (and, roughly speaking, pushing back 10000 elements
will take 10 times longer, and no more, than pushing back 1000,
and 100 times more than pushing back 100). On the other hand,
an invalid iterator or pointer can be a real pain.

--
James Kanze (Gabi Software) email: ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 14 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: john smith | last post by:
HI, when I try the following code, I get a segfault when compiled with VC.NET and g++ under cygwin. #1 vector<int> vi; #2 vector<int>::iterator ii = vi.begin(); #3 vi.reserve(10); #4 ...
7
by: hellwolf | last post by:
Hi,everyone.Because of my English level,I will try to use code to explain where I confused. //list of code: #include <iostream> #include <algorithm> #include <vector> class A{ static int...
9
by: cylin | last post by:
Dear all, Using sizeof(vector<TYPE>) will always return 16 bytes. If I have N elements ( integer ), the total memory is sizeof(vector<int>)+sizeof(int)*N, or sizeof(vector<int>)*N, or others?...
2
by: Gary Kuehn | last post by:
Is Reserve guaranteed to allocate contiguous memory? How safe is the following: vector<char> vbuff; int sz = numeric_limits<short int>::max();
7
by: Dilip | last post by:
If you reserve a certain amount of memory for a std::vector, what happens when a reallocation is necessary because I overshot the limit? I mean, say I reserve for 500 elements, the insertion of...
3
by: wenmang | last post by:
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?
9
by: Chris Roth | last post by:
I have a vector of vectors: vector< vector<double v; and have initialized it with: v( 5 ); as I know I will have 5 columns of data. At this point, I read text file data into each of the the...
23
by: Mike -- Email Ignored | last post by:
In std::vector, is reserve or resize required? On: Linux mbrc32 2.6.22.1-41.fc7 #1 SMP Fri Jul 27 18:10:34 EDT 2007 i686 athlon i386 GNU/Linux Using: g++ (GCC) 4.1.2 20070502 (Red Hat...
29
by: ab2305 | last post by:
Does standard mandates that the reserve call should initialize a container's values to its defaults, hence vector<intintVec; intVec.reserve(100) would make intVec=intVec....intVec=0 ? Thanks
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.