Create an empty vector of initial size in C++
This post will discuss how to create an empty vector of initial size in C++.
1. Using fill constructor
A simple solution to construct a vector of custom size is using the fill constructor. It takes the initial vector size and initializes it with the specified value (or the default one).
For example, the following code constructs a vector with n elements, where each element is initialized with the default value of 0.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <vector> int main() { int n = 5; std::vector<int> v(n); for (int &i: v) { std::cout << i << ' '; } return 0; } |
Output:
0 0 0 0 0
2. Using std::vector::reserve
To request a change in the capacity of a vector, we can use the std::vector::reserve function. It allocates enough space for the specified number of elements, which results in subsequent push_back operations being fast. Note that the std::vector::reserve function does not modify the size of a vector.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <vector> int main() { const int n = 5; std::vector<int> v; std::cout << v.capacity() << std::endl; // 0 std::cout << v.size() << std::endl; // 0 v.reserve(n); std::cout << v.capacity() << std::endl; // 5 std::cout << v.size() << std::endl; // 0 return 0; } |
That’s all about creating an empty vector of initial size in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)