CodeBlanks Logo Icon CodeBlanks

size and at

Learn vector management with .size() and .at().

size() and at()

Two core vector methods: size() returns the element count, at(i) accesses the element at index i. nums.size() tells how many elements there are, while nums.at(0) gives the first element.

The key difference between at and [] is that at checks bounds. An invalid index throws std::out_of_range; [] does no check, so an invalid index is undefined behavior. Prefer at for safe access.

Why is bounds checking important?

On a three-element vector, nums.at(3) throws because valid indices are 0, 1 and 2. This lets the program report a meaningful error before crashing.

The same access with nums[3] would not check; the program would read a random memory cell, producing bugs that are hard to trace later. That is why at is safer with user-supplied indices.

Practice Print three elements with at()

Declare std::vector<int> nums = {10, 20, 30};. Print the values of at(0), at(1) and at(2) on a single line separated by spaces, using std::cout.

Starter code

main.cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> nums = {10, 20, 30};
    // Print three elements with at()
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> nums = {10, 20, 30};
    std::cout << nums.at(0) << " " << nums.at(1) << " " << nums.at(2) << std::endl;
    return 0;
}

Expected output

10 20 30

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match size() and at()

Term Meaning
size() Element count
at(0) First element
at(size-1) Last element
out_of_range Out-of-bounds error

2 On a 3-element vector, what does nums.at(5) do?

main.cpp
std::vector<int> nums = {10, 20, 30};
nums.at(5);
  • Undefined behavior
  • Throws std::out_of_range Correct answer
  • Returns 5
  • Returns 30

Explanation: at checks bounds and throws std::out_of_range on an invalid index.

3 Access the second element with at()

Question
std::cout << nums.____(1) << std::endl;
Answer
std::cout << nums.at(1) << std::endl;

Explanation: at(1) accesses the second element.

All lessons in Beginner