C++ iterator::begin() Function



The C++ iterator::begin() function returns a pointer pointing to the container's first element. This pointer is bidirectional since it can point in any direction of the container. This function is available in the std namespaces map associative container class template, where key-value pairs are used to store the elements.

Iterators operate as a bridge that connects algorithms to STL containers and allows the modification of the data present inside the container. To get the desired outcome, you can use them to iterate over the container, access and assign the values, and run different operators over them.

Syntax

Following is the syntax for C++ iterator::begin() Function −

auto begin(Container& cont)  `
   -> decltype(cont.begin());

auto begin(const Container& cont)   `
   -> decltype(cont.begin());

Ty *begin(Ty (& array)[Size]);

Parameters

  • cont − it indicates the container that returns cont.begin().
  • array − an array of objects of type Ty.

Example 1

Let's consider the following example, where we are going to use the begin() function and retrive the output.

#include<iostream>
#include<iterator>
#include<vector>
using namespace std;
int main() {
   vector<int> array = {2,3,4,12,14};
   vector<int>::iterator ptr;
   cout << "The Elements are : ";
   for (ptr = array.begin(); ptr < array.end(); ptr++)
      cout << *ptr << " ";
   return 0;
}

Output

When we compile and run the above program, this will produce the following result −

The Elements are : 2 3 4 12 14 

Example 2

Consider the following example, where we are going to use map with the begin() function and retrieving the output.

#include <iostream>
#include <iterator>
#include <map>
using namespace std;
int main() {
   map<string,int> Student = {
      {"Amar", 20},
      {"Akbar", 21},
      { "Antony" ,32},
   };
   map<string,int>::const_iterator iterator;
   iterator = Student.begin();
   cout << "Name"<<"\t" <<"Age" << "\n";
   while (iterator != Student.end() ) {
      cout << iterator->first <<"\t"  << iterator->second << "\n";
      ++iterator;
   }
   cout << endl;
   return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

Name	Age
Akbar	21
Amar	20
Antony	32

Example 3

Look into the another scenario, where we are going to use begin() function and retrieving the output.

#include <iostream>
#include <vector>
int main () {
   int foo[] = {1,2,3,4,5};
   std::vector<int> bar;
   for (auto it = std::begin(foo); it!=std::end(foo); ++it)
      bar.push_back(*it);
   std::cout << "bar contains:";
   for (auto it = std::begin(bar); it!=std::end(bar); ++it)
      std::cout << ' ' << *it;
   std::cout << '\n';
   return 0;
}

Output

On running the above program, it will produce the following result −

bar contains: 1 2 3 4 5
Advertisements