I write a simple program to distinguish between the vector container size () and the capacity () function, where the capacity function is to reserve space for the vector container, without having to reallocate the memory every time the element is added, thus improving the efficiency a lot. I through a small program to study, the following is the program and running results, more concise can be seen capacity size is larger than size, because size refers to the number of elements that the container currently owns, while capacity refers to the total number of elements that the container can store before it must allocate new storage space. Needless to say, attach code and run results: #include "stdafx.h" #include <iostream> #include <vector>using namespace Std;int main () { vector<int>ivec;//when the containers are empty, output their respective sizes:cout<< "ivec.size ():" <<ivec.size () <<endl;cout< < "ivec.capacity ():" <<ivec.capacity () <<endl;for (Vector<int>::size_type Ix=0;ix!=11;++ix) Ivec.push_back (ix);//When put 11 numbers in the inside, then observe their size cout<< "ivec.size ():" <<ivec.size () <<endl;cout< < "ivec.capacity ():" <<ivec.capacity () <<endl;//the space reserved for capacity is used up here while (ivec.size ()! = Ivec.capacity ()) ivec.push_back (0);//Then add an element ivec.push_back (0);//Observe their size changes cout<< "ivec.size ():" < <ivec.size () <<endl;cout<< "ivec.capacity ():" <<ivec.capacity () <<endl;ivec.reserve (100 );//reset container size cout<< "ivec.size ():" ≪<ivec.size () <<endl;cout<< "ivec.capacity ():" <<ivec.capacity () <<endl;while ( Ivec.size ()!=ivec.capacity ()) ivec.push_back (0); ivec.push_back (0);//finally you can see that the size of capacity is either vcetor start size or redefine size, Always bigger than size, so reserve space, improve operational efficiency cout<< "ivec.size ():" <<ivec.size () <<endl;cout<< "ivec.capacity (): "<<ivec.capacity () <<endl;system (" pause "); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Here's a small program to study the memory allocation strategy provided by the standard library for vector objects, because the vector container is much more than the list and deque containers, and it's stored in a sequential way.