Reserve on vector in c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Reserve on vector in c++

I have always a dilema on reserve... We generally choose vector when size is not known and hence static array is not helpful. With this concept , is it good to reserve a big size earlier in starting itself to avoid copy constructor call ?

19th May 2020, 6:48 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Answers
+ 2
If you dont want ro reserve each time push_back do it. You can reserve for example 20-30% of full expected size. When i write the code i reserve 20-30 elements if expect that it will be up to 100 elements, 400 for 1000 and etc.
19th May 2020, 8:14 PM
george
george - avatar
+ 2
Other variant, not use vector, use some list or thomething like list.
19th May 2020, 8:15 PM
george
george - avatar
+ 2
If you really don't know how many items your vector will hold then you can just let it auto-resize. It doubles the capacity on each resize* which is a reasonable tradeoff. A lot of the time you have a pretty good estimate on how many items you need though so reserving then is a good idea. __ * It's probably implementation dependent but that's what I remember anyway.
19th May 2020, 8:52 PM
Schindlabua
Schindlabua - avatar
0
coffeeunderrun oooo thanks, i read reverse, but now fix that it about reserve))!!!
19th May 2020, 8:11 PM
george
george - avatar