Intermediate8 min readLesson 36 of 50
What is a Vector?
A vector is a dynamic array that can grow or shrink at runtime. It is the most commonly used STL container.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> scores;
scores.push_back(90);
scores.push_back(85);
scores.push_back(78);
scores.push_back(92);
cout << "Size: " << scores.size() << endl;
cout << "First: " << scores.front() << endl;
cout << "Last: " << scores.back() << endl;
cout << "Index 2: " << scores[2] << endl;
scores.pop_back(); // removes last
cout << "After pop: " << scores.size() << endl;
for (int s : scores) cout << s << " ";
cout << endl;
return 0;
}
Output:
Size: 4
First: 90
Last: 92
Index 2: 78
After pop: 3
90 85 78
Key Vector Operations
| Method | Description |
push_back(val) | Add to end |
pop_back() | Remove from end |
insert(pos, val) | Insert at iterator position |
erase(pos) | Remove at iterator position |
size() | Number of elements |
empty() | True if size == 0 |
clear() | Remove all elements |
at(i) | Bounds-checked access |
vector<string> fruits = {"Apple", "Banana", "Cherry"};
fruits.insert(fruits.begin() + 1, "Blueberry");
fruits.erase(fruits.begin()); // removes "Apple"
for (const string& f : fruits) cout << f << " ";
// Blueberry Banana Cherry
Exercise
Create a vector of integers. Read numbers from the user until they enter 0. Then print the average of all entered numbers (excluding 0).
Show Solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums;
int n;
cout << "Enter numbers (0 to stop): " << endl;
while (cin >> n && n != 0) nums.push_back(n);
if (nums.empty()) { cout << "No numbers entered." << endl; return 0; }
double sum = 0;
for (int x : nums) sum += x;
cout << "Average: " << sum / nums.size() << endl;
return 0;
}
Quiz
Which method adds an element to the end of a vector?
- A)
add() - B>
append() - C)
push_back() - D>
insert_end()
Answer
C) push_back()
Summary
vector is a dynamic array that resizes automatically.- Key operations:
push_back, pop_back, insert, erase, size, clear. - Prefer
at(i) over [i] for bounds-checked access.