Summary - std::vector
- C++ course
- Beginner
- Lesson 64/116
- 5 min
Combine push_back, size and range-based for to write a class list.
Summary: std::vector
In this group you learned std::vector: the dynamic-size array container. It starts with #include <vector>, is declared as std::vector<int> nums; and grows with push_back.
You saw three core access paths: size() counts, at(i) accesses with bounds checking, and [] accesses fast but unchecked. Finally you walked through all elements with a range-based for. These are the foundations of working with list-shaped data in C++.
Practice Sum grades with range-for
Declare std::vector<int> grades = {85, 90, 78};. Sum the grades with a range-based for, then print the average (integer division) using std::cout.
Starter code
#include <iostream>
#include <vector>
int main() {
std::vector<int> grades = {85, 90, 78};
int sum = 0;
// Sum with a range-based for and print the average
return 0;
}Sample solution
#include <iostream>
#include <vector>
int main() {
std::vector<int> grades = {85, 90, 78};
int sum = 0;
for (int g : grades) {
sum += g;
}
std::cout << sum / grades.size() << std::endl;
return 0;
}Expected output
84
Practice Build the vector and print the last element
Declare an empty std::vector<int> v. Append the values 7, 14 and 21 with push_back. Then print size() and the last element v.at(v.size()-1).
Starter code
#include <iostream>
#include <vector>
int main() {
std::vector<int> v;
// Append 7, 14, 21 with push_back; print size and last element
return 0;
}Sample solution
#include <iostream>
#include <vector>
int main() {
std::vector<int> v;
v.push_back(7);
v.push_back(14);
v.push_back(21);
std::cout << v.size() << " " << v.at(v.size() - 1) << std::endl;
return 0;
}Expected output
3 21
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the concepts
| Term | Meaning |
|---|---|
push_back |
Appends |
size() |
Counts |
at(i) |
Checked access |
for (int x : v) |
Iterates |
2 Which method checks bounds?
nums.???(i)- nums.at(i) Correct answer
- nums.push_back(i)
- nums[i]
- nums.size()
Explanation: at(i) checks bounds and throws on an invalid index.
3 Append with push_back
v.____(42);
v.push_back(42);
Explanation: v.push_back(42); appends 42 to the end of the vector.