END()
This function returns an iterator (or pointer, for arrays) that points one past the last element of a container, such as a vector, list, or array. This special position does not contain a valid element, but it marks the end boundary of the container, making it useful for iteration and comparisons. For example, in std::vector<int> v = {1, 2, 3};
, v.end()
points to the position just after 3
. It is typically used with begin()
in loops or algorithms, such as for (auto it = v.begin(); it != v.end(); ++it)
or std::sort(v.begin(), v.end());
. Since end()
marks the stopping point rather than an element itself, dereferencing it is undefined behavior. Like begin()
, C++11 introduced a generic std::end(container)
function that works with both STL containers and raw arrays for consistent iteration.
#include <iostream>
#include <iterator> // For std::begin() and std::end()
using namespace std;
int main() {
// Declare and initialize a C++ array
int numbers[] = {5, 10, 15, 20, 25};
// Use std::begin() and std::end() to iterate through the array
cout << "Array elements: ";
for (auto it = begin(numbers); it != end(numbers); ++it) {
cout << *it << " "; // Dereference iterator to access each element
}
cout << endl;
// You can also calculate the size of the array easily
size_t arraySize = end(numbers) - begin(numbers);
cout << "Array size: " << arraySize << endl;
return 0;
}
Last updated