Vector access
- C++ course
- Beginner
- Lesson 62/116
- 5 min
Learn to access vector elements with the [] operator.
Access with the [] operator
The fast way to access vector elements is the square bracket operator: nums[0] gives the first element. Unlike at it does not check bounds, but it is faster; it is preferred inside loops where the index is known to be safe.
Indices are zero-based; on a vector of n elements valid indices range from 0 to n-1. Accessing nums[n] is undefined behavior. The [] operator both reads and writes: nums[0] = 99; changes the first element.
at vs []
at and [] do the same thing but at different safety levels. nums.at(i) checks bounds and throws std::out_of_range on an invalid index. nums[i] does not check, so an invalid index is undefined behavior.
A useful habit: use [] when the index is safe and speed matters; use at when the index is untrusted or uncertain. Loops usually use [] because the loop variable already stays in range.
Practice Sum the elements with []
Declare std::vector<int> nums = {10, 20, 30, 40};. Sum all elements using the [] operator and print the result with std::cout.
Starter code
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {10, 20, 30, 40};
int sum = 0;
// Sum all elements with []
return 0;
}Sample solution
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {10, 20, 30, 40};
int sum = 0;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
}
std::cout << sum << std::endl;
return 0;
}Expected output
100
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does nums[0] = 99; do?
std::vector<int> nums = {10, 20, 30};
nums[0] = 99;- Throws an error
- Makes the vector size 99
- Sets the first element to 99 Correct answer
- Accesses the 99th element
Explanation: [] assigns, the first element becomes 99.
2 Change the first element
nums[0] ____ 99;
nums[0] = 99;
Explanation: nums[0] = 99; sets the first element to 99.
3 Match the access forms
| Term | Meaning |
|---|---|
nums[0] |
First element |
nums[size-1] |
Last element |
nums.at(0) |
Checked first element |
nums[i] = 9 |
Change i-th element |