0
0
CppConceptBeginner · 3 min read

What is begin and end in C++: Explanation and Examples

begin and end in C++ are functions that return iterators pointing to the start and one past the last element of a container or array. They let you access elements in a sequence easily, like reading a book from the first page to the last. These iterators are used in loops and algorithms to process container elements.
⚙️

How It Works

Think of a container in C++ like a row of mailboxes. begin() points to the first mailbox, and end() points just past the last mailbox, like an empty spot after the last one. This way, you know where to start and where to stop when checking mail.

In programming, begin() returns an iterator to the first element, and end() returns an iterator just after the last element. You can move from begin() to end() step by step to visit every element in order.

This mechanism helps loops and algorithms know exactly which elements to work on without going too far or missing any.

💻

Example

This example shows how to use begin() and end() to print all elements of a vector.

cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {10, 20, 30, 40, 50};
    for (auto it = numbers.begin(); it != numbers.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
    return 0;
}
Output
10 20 30 40 50
🎯

When to Use

Use begin() and end() whenever you want to access or process all elements in a container like std::vector, std::list, or arrays. They are essential for loops, algorithms, and range-based for loops.

For example, if you want to sum all numbers in a list or find a specific item, begin() and end() help you move through the container safely and efficiently.

Key Points

  • begin() returns an iterator to the first element.
  • end() returns an iterator just past the last element.
  • They are used to loop through containers safely.
  • Commonly used with standard containers like vector, list, and arrays.
  • Enable use of standard algorithms like std::sort and std::find.

Key Takeaways

begin() and end() provide iterators to start and just past the end of a container.
They allow safe and easy traversal of elements in loops and algorithms.
Use them with standard containers and arrays to access all elements.
They are fundamental for writing clean and efficient C++ code involving sequences.