C++ Standard Library C++ STL Library

C++ <string> - cbegin() Function



The C++ string::cbegin function returns the constant iterator (const_iterator) pointing to the first character of the string. Please note that, Unlike the string::front function, which returns a direct reference to the first character, it returns the const_iterator pointing to the same character of the string.

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 string character is not itself constant.

Syntax

const_iterator cbegin() const noexcept;

Parameters

No parameter is required.

Return Value

A const_iterator to the beginning of the string.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the string::cbegin function returns the const_iterator pointing to the first character of the string called str.

#include <iostream>
#include <string>

using namespace std;
 
int main (){
  string str = "Learn C++";
  string::const_iterator cit;

  cit = str.cbegin();
  cout<<*cit<<" ";
  cit++;
  cout<<*cit<<" ";
  cit++;
  cout<<*cit<<" ";
  return 0;
}

The output of the above code will be:

L e a

Example:

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

#include <iostream>
#include <string>

using namespace std;
 
int main (){
  string str = "Learn C++";
  string::const_iterator cit;

  for(cit = str.cbegin(); cit != str.cend(); ++cit)
    cout<<*cit<<" ";

  return 0;
}

The output of the above code will be:

L e a r n   C + + 

❮ C++ <string> Library