push_back
- C++ course
- Beginner
- Lesson 60/116
- 5 min
Learn to add elements to a vector with push_back.
Adding elements with push_back
The common way to add an element to a vector is the push_back method. The call nums.push_back(10); appends the value to the end of the vector and increases the size by one. Creating an empty vector and calling push_back repeatedly is the quickest way to build a list that grows as you collect data.
The method name means 'push toward the back'; the element is always placed at the end. It does not insert in the middle; push_back only appends.
The size grows automatically
push_back increases the vector size by one on each call. On a three-element vector, calling nums.push_back(40); makes the size 4 and nums[3] now gives 40.
This automatic growth is the most important difference from C-style arrays. A C-style array has a size fixed at compile time; with std::vector the size changes at runtime. Memory management is automatic too; you just call push_back.
Practice Add three elements with push_back
Declare an empty std::vector<int> nums;. Append the values 5, 10 and 15 in order with push_back. Then print size().
Starter code
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums;
// Add 5, 10, 15 with push_back and print size()
return 0;
}Sample solution
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums;
nums.push_back(5);
nums.push_back(10);
nums.push_back(15);
std::cout << nums.size() << std::endl;
return 0;
}Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the push_back call
nums.____(10);
nums.push_back(10);
Explanation: push_back(10) appends the value.
2 After nums.push_back(40); what is the size? (nums started with 3)
std::vector<int> nums = {10, 20, 30};
nums.push_back(40);- 4 Correct answer
- 3
- 30
- 40
Explanation: the size goes from 3 to 4.
3 Match push_back behaviour
| Term | Meaning |
|---|---|
push_back |
Appends an element |
size() |
Returns the count |
nums[0] |
Accesses first element |
std::vector |
Dynamic array container |