BEGIN()
This function is used to obtain an iterator (or pointer, in the case of arrays) that points to the first element of a container, such as a vector, list, map, or array. It allows developers to access and iterate through the contents of the container in a standardized way. For example, in std::vector<int> v = {10, 20, 30};, calling v.begin() returns an iterator pointing to the element 10. The begin() function is often used in combination with end() in loops or algorithms from the <algorithm> library, like std::sort(v.begin(), v.end());. In C++11 and later, there’s also a non-member version std::begin(container) that works with both STL containers and raw arrays, providing a consistent and generic way to start 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