In a C++ standard container, what does end() refer to, and why must you never dereference it?
answer
- half-open, not closed
- one past the last
- begin() == end() means empty
- find reports failure with it
basics
~20 send() returns the past-the-end iterator: a position one past the last element, not the last element itself. Container ranges are half-open, [begin, end), so begin() == end() means empty, and dereferencing end() is undefined behaviour.
solid answer
~40 sEvery standard container describes its elements as the half-open range `[begin(), end())`. `begin()` refers to the first element; `end()` is the **past-the-end** iterator, a position one beyond the last element, the way a pointer may point one past the end of an array. It is a valid value to compare and copy, but there is no element behind it, so `*end()` is undefined behaviour. The design pays off everywhere: a loop runs `while (it != c.end())`, an empty container has `begin() == end()`, `end() - begin()` equals `size()` for a vector, and algorithms such as `std::find` return `end()` to say "not found". To reach the last element, use `back()` or `std::prev(end())`, and only after checking the container is not empty.
code
cpp · 23 lines#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main() {
const std::vector<std::string> playlist{"Intro", "Verse", "Chorus"};
// [begin, end): end() is one past "Chorus", not "Chorus" itself.
std::cout << playlist.end() - playlist.begin() << '\n'; // 3 == size()
auto it = std::find(playlist.begin(), playlist.end(), "Bridge");
if (it == playlist.end()) {
std::cout << "not found\n"; // never write *it here
}
std::vector<std::string> empty;
std::cout << std::boolalpha << (empty.begin() == empty.end()) << '\n';
if (!playlist.empty()) {
std::cout << *std::prev(playlist.end()) << '\n'; // last element: Chorus
}
}go deeper
Recall the half-open range: begin() is the first element and end() is one past the last. Say plainly that dereferencing end() is undefined behaviour and that find returns end() when nothing matches.
Explain why half-open ranges make the empty case and the loop condition fall out naturally, and how const_iterator, cbegin() and back() fit into everyday code.
Show the habit of checking every search result against end() before use, and spotting code reviews where back(), front() or *prev(end()) run on a container that can be empty.
Frame the convention as a contract the whole library shares: any type of yours that exposes begin() and end() in the same half-open way works with range-for and every standard algorithm.
## Half-open ranges: the convention behind every container Every standard container exposes its elements through two iterators: `begin()` and `end()`. An **iterator** is an object that refers to a position in a sequence; you read the element there with `*it`, move to the next position with `++it`, and compare two positions with `==` and `!=`. The pair describes a **half-open range**, written `[begin, end)`: it includes the element at `begin()` and stops *before* `end()`. So `end()` is not the last element. It is the **past-the-end** iterator, a position one beyond the last element. The standard models this on raw pointers: just as a pointer may point one past the end of an array, every iterator type has a past-the-end value for its sequence, and the library never assumes that value is dereferenceable. For a `std::vector<std::string>` holding `"Intro"`, `"Verse"` and `"Chorus"`: | expression | refers to | |---|---| | `begin()` | `"Intro"` | | `begin() + 2` | `"Chorus"`, the last element | | `end()` | one past `"Chorus"`; no element | | `end() - begin()` | `3`, the same as `size()` | ## Why the design is half-open A closed range, where the end names the last element, would need special cases everywhere. The half-open form removes them: - **The empty case is free.** An empty container has `begin() == end()`, so a loop `for (auto it = c.begin(); it != c.end(); ++it)` runs zero times without any extra check. A closed range has no way to name "the last element" of nothing. - **Lengths subtract cleanly.** For a vector, `end() - begin()` equals `size()`, with no plus-one corrections. - **Ranges split without overlap.** Any middle iterator `m` divides `[begin, end)` into `[begin, m)` and `[m, end)`, which algorithms such as a merge or a partition rely on. - **Failure has a value.** Searching algorithms return the end of the range they were given to mean "not found". `std::find(v.begin(), v.end(), x)` returns `v.end()` when no element equals `x`. ## Dereferencing end() is undefined behaviour Because no element lives at `end()`, `*v.end()` is **undefined behaviour**: the standard places no requirement on what happens. In practice it may read whatever memory lies after the buffer, read a container's internal sentinel node, or crash. It will not throw an exception, because standard iterators do not check their own validity. The bug usually appears indirectly: 1. A search result is used without a check: `auto it = m.find(key); use(it->second);` when `key` is absent. 2. The last element is taken on a container that may be empty: `v.back()` and `*std::prev(v.end())` are both undefined on an empty vector. 3. A loop condition is written with `<=`: `it <= v.end()` visits `end()` itself on the final pass. 4. A loop increments past `end()`, which is undefined too; the range does not wrap around to `begin()`. The habit that prevents all four is short: compare every iterator from a search against the range's end before using it, and check `empty()` before `front()` or `back()`. ## Reaching the last element To read the final element, use `back()`, which states the intent, or `*std::prev(c.end())`, which works for any container with bidirectional iterators (`std::vector`, `std::deque`, `std::list`, `std::map`). A `std::forward_list` iterator only moves forward, so it has no `back()` and no `std::prev`. Either way, check `!c.empty()` first. ## const_iterator and the c-prefixed functions Each container offers two iterator types: - `iterator`, through which elements can be modified, returned by `begin()` and `end()` on a non-const container; - `const_iterator`, which only reads, returned by `cbegin()` and `cend()` always, and by `begin()` and `end()` on a const container. The past-the-end rules are identical for both: `cend()` is just as undereferenceable as `end()`. Reversed traversal uses `rbegin()` and `rend()`, where `rend()` is the position before the first element in the forward sense and is equally off limits. ## What interviewers listen for A good answer names the half-open range, says plainly that `end()` is one past the last element and that dereferencing it is undefined behaviour, and connects the convention to everyday code: loop conditions with `!=`, `find` returning `end()`, the empty check before `back()`. Mentioning that the same contract lets your own types work with range-based `for` and the standard algorithms shows you see it as a library-wide rule rather than a quirk of one container.
- How do you get the last element of a std::vector safely?Check `!v.empty()` first, then use `v.back()` or `*std::prev(v.end())`; both have undefined behaviour on an empty vector because there is no element to return. `v.back()` states the intent best. For a `std::list` or `std::map`, `std::prev(end())` works because their iterators are bidirectional; a `std::forward_list` iterator cannot step backwards at all.
- What is the difference between begin() and cbegin() on a std::vector?On a non-const vector, `begin()` returns `iterator`, through which you can modify elements, while `cbegin()` always returns `const_iterator`, which only reads. On a const vector `begin()` already returns `const_iterator`. Reaching for `cbegin()` (or iterating a `const&`) documents that a loop does not write, and the compiler rejects an accidental assignment through it.
end() is the empty slot after the last song in a jukebox rack: you can point at it to say where the songs stop, but there is no record there to play.
- Says end() refers to the last element of the container
- Writes *v.end() or *std::find(...) without checking against end()
- Calls v.back() on a vector that may be empty
- Loops with it <= v.end() instead of it != v.end()
- Thinks begin() == end() signals an error rather than an empty range