Declaring vectors
- C++ course
- Beginner
- Lesson 59/116
- 5 min
Learn to create dynamic arrays with std::vector.
What is std::vector?
std::vector is the dynamic-size array container of the C++ standard library. Unlike C-style arrays, its size can grow and shrink at runtime; it expands automatically as you add elements with push_back.
To use it you must add the #include <vector> header. The declaration looks like std::vector<int> nums;: the type goes inside angle brackets, and you do not have to give a size. Creating an empty vector and filling it later is a common pattern.
Empty vector and initial values
You can declare a vector in two common ways. The first is to start empty: std::vector<int> nums; — here nums is empty, with size zero. The second is with initial values: std::vector<int> nums = {10, 20, 30}; — the braces produce a three-element vector.
Whether you start empty or filled, the size can change later. Starting empty and filling with push_back is a common technique when working with user data.
Practice Declare an empty vector and print its size
Declare an empty std::vector<int> nums; and print its size with size() using std::cout.
Starter code
#include <iostream>
#include <vector>
int main() {
// Declare an empty vector and print its size
return 0;
}Sample solution
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums;
std::cout << nums.size() << std::endl;
return 0;
}Expected output
0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which header must be added to use std::vector?
#include <???>- <iostream>
- <string>
- <array>
- <vector> Correct answer
Explanation: the <vector> header brings in the std::vector template.
2 Initialize the vector
std::vector<int> nums ____ {10, 20, 30};
std::vector<int> nums = {10, 20, 30};
Explanation: = gives the initial values.
3 Match the vector parts
| Term | Meaning |
|---|---|
std::vector |
Container name |
<int> |
Element type |
nums |
Vector name |
{10, 20, 30} |
Initial values |