CodeBlanks Logo Icon CodeBlanks

begin and end

Learn iterator ranges with begin() and end().

begin and end

Every STL container offers two member functions: begin() returns an iterator to the first element, and end() returns the position one past the last element (past-the-end). Together they define a range: [begin, end).

This range is half-open: begin is included, end is excluded. Loops use it != v.end(), not <. That is because every iterator category supports != but only random access iterators support <. So != is more portable.

Half-open range

The half-open nature of [begin, end) makes empty containers easy. For an empty vector begin() == end() and the loop runs zero times. No special empty check is needed.

end() is never dereferenced. The position it points at is not a valid element. It is used only for comparison. This design is consistent across all STL algorithms such as std::find and std::sort: they all expect a [begin, end) range. That is why this range idea is the foundation of the STL.

Practice Print with begin and end

Print the vector v = {5, 4, 3, 2, 1} in a while loop using v.begin() and v.end(). Add a space after each element.

Starter code

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

int main() {
    std::vector<int> v = {5, 4, 3, 2, 1};
    // Print using begin and end
    return 0;
}

Sample solution

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

int main() {
    std::vector<int> v = {5, 4, 3, 2, 1};
    auto it = v.begin();
    while (it != v.end()) {
        std::cout << *it << " ";
        ++it;
    }
    return 0;
}

Expected output

5 4 3 2 1

Questions and answers

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

1 Complete the loop condition

Question
auto it = v.begin();
while (it != v.____()) {
    ++it;
}
Answer
auto it = v.begin();
while (it != v.end()) {
    ++it;
}

Explanation: v.end() returns the position past the last element.

2 What does the v.end() iterator represent?

main.cpp
std::vector<int> v = {1, 2, 3};
auto e = v.end();
  • The first element
  • The position past the last element Correct answer
  • The last element
  • An empty container

Explanation: end() is the position past the last and is never dereferenced.

3 Match each concept to its description

Term Meaning
v.begin() Iterator to first
v.end() Past the last
[begin, end) Half-open range
begin == end Empty container

All lessons in Intermediate