Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initial capacity of vector in C++

What is the capacity() of an std::vector which is created using the default constuctor? I know that the size() is zero. Can we state that a default constructed vector does not call heap memory allocation?

This way it would be possible to create an array with an arbitrary reserve using a single allocation, like std::vector<int> iv; iv.reserve(2345);. Let's say that for some reason, I do not want to start the size() on 2345.

For example, on Linux (g++ 4.4.5, kernel 2.6.32 amd64)

#include <iostream> #include <vector>  int main() {   using namespace std;   cout << vector<int>().capacity() << "," << vector<int>(10).capacity() << endl;   return 0; } 

printed 0,10. Is it a rule, or is it STL vendor dependent?

like image 626
Notinlist Avatar asked Sep 04 '12 20:09

Notinlist


People also ask

What is the initial capacity of vector?

Default initial capacity of Vector is 10. java. util. Vector default constructor defines size of 10.

What is the default capacity of vector in C++?

Default value of the Vector: The default value of a vector is 0.

How do you find the capacity of a vector?

The C++ function std::vector::capacity() returns the size of allocate storage, expressed in terms of elements. This capacity is not necessarily equal to the size of vector. It can be equal or greater than vector size. The theoretical limit on vector size is given by member max_size.

Are vectors initialized with 0?

Any other number can be used. A vector can be initialized with all zeros in three principal ways: A) use the initializer_list, B) use the assign() vector member function to an empty vector (or push_back()), or C) use int or float as the template parameter specialization for a vector of initially only default values.


2 Answers

The standard doesn't specify what the initial capacity of a container should be, so you're relying on the implementation. A common implementation will start the capacity at zero, but there's no guarantee. On the other hand there's no way to better your strategy of std::vector<int> iv; iv.reserve(2345); so stick with it.

like image 107
Mark Ransom Avatar answered Oct 14 '22 08:10

Mark Ransom


Storage implementations of std::vector vary significantly, but all the ones I've come across start from 0.

The following code:

#include <iostream> #include <vector>  int main() {   using namespace std;      vector<int> normal;   cout << normal.capacity() << endl;      for (unsigned int loop = 0; loop != 10; ++loop)   {       normal.push_back(1);       cout << normal.capacity() << endl;   }      cin.get();   return 0; } 

Gives the following output:

0 1 2 4 4 8 8 8 8 16 16 

under GCC 5.1, 11.2 - Clang 12.0.1 and:

0 1 2 3 4 6 6 9 9 9 13 

under MSVC 2013.

like image 30
metamorphosis Avatar answered Oct 14 '22 08:10

metamorphosis