begin()
functionThe begin()
function is used to get the iterator that points to the first element of a vector. This function is available in the <vector>
header file.
The begin()
function does not accept any parameters.
This function returns an iterator that points to the first element in the vector. We can dereference the returned iterator and get the first element in the vector. If the vector is empty, the iterator cannot be dereferenced.
Let’s look at the code and see how the begin()
function is used.
#include <iostream>#include <vector>using namespace std;int main() {vector<int> vec = {1,2,3,4,5,6,7,8,9,10};vector<int> empty_vec = {};auto it = vec.begin();cout << *it;// cout << "\n";// auto empty_vec_it = empty_vec.begin();// cout << *empty_vec_it;return 0;}
begin()
function.end()
functionThe end()
function is used to get the iterator that points to the one-past-the-last element of the vector. This function is available in the <vector>
header file.
The end()
function does not accept any parameters.
This function returns an iterator that points to the one-past-the-last element in the vector. If we dereference the returned vector, we would get a garbage value.
To get the last element, we need to subtract 1
from the returned iterator, i.e., go back by one position. If the vector is empty, then the iterator cannot be dereferenced.
Now, let’s look at the code and see how the end()
function is used.
#include <iostream>#include <vector>using namespace std;int main() {vector<int> vec = {1,2,3,4,5,6,7,8,9,10};vector<int> empty_vec = {};auto it = vec.end();cout << *(it - 1);// cout << "\n";// auto empty_vec_it = empty_vec.end();// cout << *empty_vec_it;return 0;}
end()
function.The begin()
and end()
functions are utilized when in-built functions in C++ are used to pass the start and end iterator to those functions. Some examples of such functions are sort()
, max_element()
, min_element()
, etc.