What are the vector.begin() and vector.end() functions in C++?

The begin() function

The 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.

Parameters

The begin() function does not accept any parameters.

Return value

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.

Code

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;
}

# Explanation

  • In lines 1 and 2, we import the required packages.
  • In lines 6 and 7, we create two vectors, one contains integers and the other is empty.
  • In line 8, we call the begin() function.
  • In line 9, we dereference the iterator to get the first element of the vector.
  • If you uncomment the lines 10 to 13, you will get an error because the vector is empty and the iterator cannot be dereferenced.

The end() function

The 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.

Parameters

The end() function does not accept any parameters.

Return value

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.

Code

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;
}

# Explanation

  • In lines 1 and 2, we import the required packages.
  • In lines 6 and 7, we create two vectors, one contains integers and the other one is empty.
  • In line 8, we call the end() function.
  • In line 9, we dereference the iterator and subtract one to get the last element of the vector.
  • If you uncomment lines 10 to 13, you will get an error, because the vector is empty and the iterator cannot be dereferenced.

Where can these functions be used?

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.

Free Resources