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? 7 3009
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 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?
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.capaci ty()<<std::endl ;
// VecInt.push_bac k( 1 );
for(size_t i(0); i < 11; ++i){
VecInt.push_bac k( i );
}
std::cout<<" size="<<VecInt. size()<<" cap="
<<VecInt.capaci ty()<<std::endl ;
for(size_t i(0); i < 50; ++i){
VecInt.push_bac k( i );
}
std::cout<<" size="<<VecInt. size()<<" cap="
<<VecInt.capaci ty()<<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
On Fri, 21 Apr 2006 22:20:46 GMT, "BobR"
<Re***********@ worldnet.att.ne t> 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
In article <44************ *@news.utanet.a t>, rp*****@yahoo.c om (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
On Sat, 22 Apr 2006 14:17:50 GMT, Howard Hinnant
<ho************ @gmail.com> wrote: In article <44************ *@news.utanet.a t>, rp*****@yahoo.c om (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?
In article <44************ *@news.utanet.a t>, rp*****@yahoo.c om (Roland Pibinger) wrote: On Sat, 22 Apr 2006 14:17:50 GMT, Howard Hinnant <ho************ @gmail.com> wrote:In article <44************ *@news.utanet.a t>, rp*****@yahoo.c om (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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: enzo |
last post by:
hi all,
i don't understand what's wrong:
1)
std::vector<double> p(10);
doesn't compile:
|
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 contains another std::vector<CPosition>. Because one of the players is the
client itself (and the size of the vector<CPlayer> doesn't change during a game), i thought i could store a
std::vector<CPlayer>::iterator "localplayer" that points to the...
|
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 perfomance than if I first define the
vector of a given size, then write to the elements with myvec =
However, I'm currently thinking that it isn't feasible to obtain the vector
size, so really need to resize the vector dynamically as I go. Is...
|
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 only achieves
half the job. Here is how I would use std::remove_if to remove elements from
std::vector based on predicate:
v.erase(std::remove_if(v.begin(), v.end(), pred), v.end());
After that line is executed I cannot get back the elements...
|
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;
std::vector<double>::size_type size = src.size();
dest.reserve(size);
for (std::vector<int>::size_type i = 0;
| |
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?
|
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 types or
std::vector<int>.
So where I would use an int* and reallocate it from time to time in C,
and randomly access it via , then I figure to copy the capacity and
reserve methods, because I just need a growable array.
I get to considering...
|
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 elements of the vector.
Thank you !
Mathieu
Code:
|
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 4.1.2-12)
The program below fails, but if the reserve(en)
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |