C++ Standard Library C++ STL Library

C++ map - cbegin() Function



The C++ map::cbegin function returns the constant iterator (const_iterator) pointing to the first element of the map.

C++ cbegin cend

Note: A const_iterator is an iterator that points to constant value. The difference between iterator and const_iterator is that the const_iterator cannot be used to modify the content it points to, even if the map element is not itself constant.

Note: Map is an ordered data container which implies all its elements are ordered all the time.

Syntax

const_iterator cbegin() const noexcept;

Parameters

No parameter is required.

Return Value

A const_iterator to the beginning of the sequence container.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the map::cbegin function returns the const_iterator pointing to the first element of the map called MyMap.

#include <iostream>
#include <map>
using namespace std;
 
int main (){
  map<int, string> MyMap;
  map<int, string>::const_iterator cit;

  MyMap[101] = "John";
  MyMap[102] = "Marry";
  MyMap[103] = "Kim";
  MyMap[104] = "Jo";
  MyMap[105] = "Ramesh";

  cit = MyMap.cbegin();
  cout<<cit->first<<" "<<cit->second<<"\n";
  cit++;
  cout<<cit->first<<" "<<cit->second<<"\n";
  cit++;
  cout<<cit->first<<" "<<cit->second<<"\n";
  return 0;
}

The output of the above code will be:

101 John
102 Marry
103 Kim

Example:

Lets see another example of map where map::cbegin function is used with map::cend function to specify a range including all elements of the map container.

#include <iostream>
#include <map>
using namespace std;
 
int main (){
  map<string, int> MyMap;
  map<string, int>::const_iterator cit;

  MyMap["John"] = 2500;
  MyMap["Jack"] = 2600;
  MyMap["Ella"] = 2000;
  MyMap["Nora"] = 3000;
  MyMap["Adam"] = 3100;

  cout<<"MyMap contains: \n ";
  for(cit = MyMap.cbegin(); cit != MyMap.cend(); ++cit)
    cout<<cit->first<<"  "<<cit->second<<"\n ";

  return 0;
}

The output of the above code will be:

MyMap contains: 
 Adam  3100
 Ella  2000
 Jack  2600
 John  2500
 Nora  3000

❮ C++ <map> Library

5