Traversal Basics
Sveip for å vise menyen
The begin() and end() member functions are used in C++ standard library containers to provide iterators that mark the start and one-past-the-end positions of the container, respectively.
Used together, begin() and end() define the valid range of elements. The iterator from begin() points to the first element, while end() marks the position just after the last element and does not refer to valid data. This half-open range [begin(), end()) includes all elements and lets algorithms detect the end of iteration without accessing invalid memory.
main.cpp
123456789101112131415#include <iostream> #include <list> int main() { std::list<int> numbers = {10, 20, 30, 40, 50}; // Iterator 'it' starts at begin(), will stop at end() for (auto it = numbers.begin(); it != numbers.end(); ++it) { // Safe to dereference 'it' here: it points to a valid element std::cout << *it << " "; std::cout << std::endl; // Note: 'it' never equals end() inside the loop body }
In this example, you see a typical traversal pattern using iterators. The loop starts with an iterator at begin() and continues as long as the iterator does not equal end(). Inside the loop, dereferencing the iterator is always safe because it points to a valid element. The iterator is never equal to end() within the loop body, which prevents you from accessing memory that does not belong to the container. The structure of this loop is critical: it ensures that you only access elements that actually exist in the container, and never attempt to read past the end.
main.cpp
12345678910#include <iostream> #include <list> int main() { std::list<int> numbers = {100, 200, 300}; auto it = numbers.end(); // 'it' points one past the last element // Mistakenly trying to dereference end() - undefined behavior! std::cout << *it << std::endl; // This is a common mistake }
If you dereference the iterator returned by end(), you invoke undefined behavior. Because end() does not point to a valid element, this can crash the program or lead to unpredictable results. The inclusive/exclusive boundary pattern [begin(), end()) prevents this by ensuring only valid elements are accessed. The first example follows this rule, while the second shows what can go wrong when the exclusive boundary of end() is ignored.
The [begin(), end()) iteration pattern is consistent across all standard library containers that support iterators, including std::vector, std::list, std::deque, std::set, and others. This makes it easy to write generic code that works with any container type.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår