473,404 Members | 2,174 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,404 software developers and data experts.

semantics of std::vector.reserve()


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 501st element
is going to cause some more allocation -- for arguments sake if the
vector re-grows to accomodate 1000 elements, I play around with it and
completely erase everything in it after I am done. Now how much does
the vector hold? Do I need to re-reserve 500? Does it stay on with
the formerly re-adjusted capacity of 1000?

Apr 21 '06 #1
7 2972

Dilip wrote:
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 501st element
is going to cause some more allocation -- for arguments sake if the
vector re-grows to accomodate 1000 elements, I play around with it and
completely erase everything in it after I am done. Now how much does
the vector hold? Do I need to re-reserve 500? Does it stay on with
the formerly re-adjusted capacity of 1000?


What do you mean, "how much does the vector hold"? A vector has two
important properties, size and capacity. The functions to change them
are
resize() and reserve(). Capacity is at least as large as the size,
obviously.
If you clear the vector, you change its size but not its capacity.
Clearly
in your example the size is 0 and the capacity _at least_ 1000.

(And reserve(500) reserves at least 500, but reserving 512 would be
legal as well. Check capacity to be sure)

HTH,
Michiel Salters

Apr 21 '06 #2
Mi*************@tomtom.com wrote:
Dilip wrote:
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 501st element
is going to cause some more allocation -- for arguments sake if the
vector re-grows to accomodate 1000 elements, I play around with it and
completely erase everything in it after I am done. Now how much does
the vector hold? Do I need to re-reserve 500? Does it stay on with
the formerly re-adjusted capacity of 1000?
If you clear the vector, you change its size but not its capacity.


Awesome -- this is what I wanted to hear. However...
Clearly
in your example the size is 0 and the capacity _at least_ 1000.


If I reserve 500 I take it that space for _atleast_ 500 elements is
created. So if I put an upper limit of 500 in my code to do some
processing and clear the vector post-processing, ideally there should
be no reason why the vector will ever have a need to re-adjust its
memory, right?

Apr 21 '06 #3

Dilip wrote in message ...

If I reserve 500 I take it that space for _atleast_ 500 elements is
created. So if I put an upper limit of 500 in my code to do some
processing and clear the vector post-processing, ideally there should
be no reason why the vector will ever have a need to re-adjust its
memory, right?


Y'know, sometimes you can read 'till you are blue in the face and still not
get a clear picture. Do some tests to solidify it in your mind:

std::vector<int> VecInt(10);
std::cout<<" size="<<VecInt.size()<<" cap="
<<VecInt.capacity()<<std::endl;
// VecInt.push_back( 1 );
for(size_t i(0); i < 11; ++i){
VecInt.push_back( i );
}
std::cout<<" size="<<VecInt.size()<<" cap="
<<VecInt.capacity()<<std::endl;
for(size_t i(0); i < 50; ++i){
VecInt.push_back( i );
}
std::cout<<" size="<<VecInt.size()<<" cap="
<<VecInt.capacity()<<std::endl;
// etc.
// - output -
// size=10 cap=10
// size=21 cap=40
// size=71 cap=80

Notice how every time it exceeds capacity it doubles the capacity[1]?
Now try your own experiment. Set (reserve()) 500, then fill it with 501
elements and see if it doesn't go to cap=1000. Add 500 more elements, what do
you get for capacity()?

If the vector keeps doubling, eventually it will run out of memory, where if
you had set the capacity in the beginning, it may have fit in memory (memory
gets 'fragmented' sometimes, and the vector allocator won't be able to find a
big enough 'solid' chunk to continue.)

That help any?
[1] - (on my compiler implementation. YMMV)
--
Bob R
POVrookie
Apr 21 '06 #4
On Fri, 21 Apr 2006 22:20:46 GMT, "BobR"
<Re***********@worldnet.att.net> wrote:
Notice how every time it exceeds capacity it doubles the capacity[1]?
Now try your own experiment. Set (reserve()) 500, then fill it with 501
elements and see if it doesn't go to cap=1000. Add 500 more elements, what do
you get for capacity()?
AFAIK, popular implementations produce this behavior for push_back(),
insert(), ... only, but not for reserve. E.g. the following copies the
vector contents twice (if capacity < 500):

VecInt.reserve(500);
VecInt.reserve(501);

Moreover, clear() is not guaranteed to preserve the capacity.
[1] - (on my compiler implementation. YMMV)


YIMV (Your Implementation May Vary)
Roland Pibinger
Apr 22 '06 #5
In article <44*************@news.utanet.at>,
rp*****@yahoo.com (Roland Pibinger) wrote:
Moreover, clear() is not guaranteed to preserve the capacity.


According to the standard, vector::clear() is guaranteed to preserve
capacity. One high profile implementation violated this guarantee in a
few versions but is standard conforming in its latest version.

-Howard
Apr 22 '06 #6
On Sat, 22 Apr 2006 14:17:50 GMT, Howard Hinnant
<ho************@gmail.com> wrote:
In article <44*************@news.utanet.at>,
rp*****@yahoo.com (Roland Pibinger) wrote:
Moreover, clear() is not guaranteed to preserve the capacity.


According to the standard, vector::clear() is guaranteed to preserve
capacity.


Where did you find that in the C++ Standard?
Apr 22 '06 #7
In article <44*************@news.utanet.at>,
rp*****@yahoo.com (Roland Pibinger) wrote:
On Sat, 22 Apr 2006 14:17:50 GMT, Howard Hinnant
<ho************@gmail.com> wrote:
In article <44*************@news.utanet.at>,
rp*****@yahoo.com (Roland Pibinger) wrote:
Moreover, clear() is not guaranteed to preserve the capacity.
According to the standard, vector::clear() is guaranteed to preserve
capacity.


Where did you find that in the C++ Standard?


23.1.1p4, Sequence requirements:

The semantics of a.clear() is erase(begin(), end()).

clear() is not otherwise defined for vector.

Same table:

erase(q1, q2): erases the elements in the range [q1, a2).

23.2.4.3p3-p5 goes on to further define erase(iter,iter) for vector but
does not address capacity issues one way or the other.

23.2.4.2p2-p5: Defines vector::reserve. The definition includes:
After reserve(), capacity() is greater or equal to the argument of reserve if
reallocation happens; and equal to the previous value of capacity()
otherwise. Reallocation happens at this point if and only if the current
capacity is less than the argument of reserve().
There is a note which further explains:
It is guaranteed that no reallocation takes place during insertions that
happen after a call to reserve() until the time when an insertion would make
the size of the vector greater than the size specified in the most recent
call to reserve().
Consider this code:

vector<int> v;
v.reserve(100);
v.resize(100);
v.clear();
v.resize(100);

According to the note above, neither the first nor second call to resize
should not be allowed to reallocate because of the preceding call to
reserve. There is no part of the definition of clear or erase which
otherwise grants such leeway.

Additionally the working draft for C++0X has already been changed via DR
329 to make it more clear that "most recent" really means "largest":
It is guaranteed that no reallocation takes place during insertions that
happen after a call to reserve()
until the time when an insertion would make the size of the vector greater
than the value of capacity().


There is interest in adding functionality to the C++0X vector allowing a
"shrink-to-fit" functionality as std::string already enjoys with its
reserve member.

http://www.open-std.org/jtc1/sc22/wg...70.html#add-me
mber-resize-capacity-to-vector-and-basic-string

This would have the effect of negating the "largest" reserve. Currently
the only way to achieve such functionality is to allocate a new smaller
buffer, copy the old data into it, and swap buffers. However here is a
proposal:

http://www.open-std.org/jtc1/sc22/wg...006/n1953.html

which would allow the possibility that the vector could shrink in place
(e.g. without reallocating a new smaller buffer). Neither proposal has
been turned down, but neither is enjoying overwhelming support either.

-Howard
Apr 22 '06 #8

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

Similar topics

4
by: enzo | last post by:
hi all, i don't understand what's wrong: 1) std::vector<double> p(10); doesn't compile:
18
by: Janina Kramer | last post by:
hi ng, i'm working on a multiplayer game for a variable number of players and on the client side, i'm using a std::vector<CPlayer> to store informatik about the players. CPlayer is a class that...
11
by: Steve | last post by:
Hi, I'm using a std::vector to store a list of user defined objects. The vector may have well over 1000 elements, and I'm suffering a performance hit. If I use push_back I get a much worse...
6
by: Jason Heyes | last post by:
What is a good way of removing elements from std::vector so that the elements removed satisfy a predicate and end up stored in another std::vector. It seems as though the algorithm std::remove_if...
20
by: Anonymous | last post by:
Is there a non-brute force method of doing this? transform() looked likely but had no predefined function object. std::vector<double> src; std::vector<int> dest; ...
8
by: Alex Vinokur | last post by:
What is relation between std::vector's reserve() and erase()/clear()? vector<int> v; v.reserve(100); v.resize(100); v.erase(v.end()); How many elements are reserved here: 100 or 99?
8
by: Ross A. Finlayson | last post by:
I'm trying to write some C code, but I want to use C++'s std::vector. Indeed, if the code is compiled as C++, I want the container to actually be std::vector, in this case of a collection of value...
4
by: mathieu | last post by:
Hello, I am looking at the API of std::vector but I cannot find a way to specify explicitely the size of my std::vector. I would like to avoid vector::resize since it first initializes 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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.