Mastering C++
Vectors Part 2
Understand VectorsAdding Values to the Vector Using push_back()
When you need to add values to your vector, you can use the function push_back(), which will append the new value to the end of the vector. This is helpful when you're collecting data one item at a time like adding grades, temperatures, or any growing list of values.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers;
numbers.push_back(5); // {5}
numbers.push_back(10); // {5, 10}
numbers.push_back(15); // {5, 10, 15}
for (int i = 0; i < numbers.size(); i++) {
cout << numbers[i] << " ";
}
return 0;
}OUTPUT:
5 10 15Inserting a Value Using insert()
The insert() function lets you add a value at any position in the vector. When you insert a value, everything from that position onward is shifted one space to the right to make room.
Members only
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 21 more lessons in Mastering C++.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.