Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ string::cend function is used to return the constant iterator (const_iterator) pointing to the past-the-last character of the string. The past-the-last character of the string is the theoretical character that follows the last character. It does not point to any character, and hence could not be dereferenced.

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 contents it points to, even if the string character is not itself constant.

Syntax

const_iterator cend() const noexcept;

Parameters

No parameter is required.

Return Value

A const_iterator to the past-the-last character of the string.

Time Complexity

Constant i.e, Θ(1).

Example:

In the below example, the string::cend function is used to return the const_iterator pointing to the past-the-last character of the string MyString.

#include <iostream>
#include <string>
using namespace std;
 
int main (){
  string MyString = "Learn C++";
  string::const_iterator cit;

  cit = MyString.cend();
  cit--;
  cout<<*cit<<" ";
  cit--;
  cout<<*cit<<" ";
  cit--;
  cout<<*cit<<" ";
  return 0;
}

The output of the above code will be:

+ + C

Example:

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

#include <iostream>
#include <string>
using namespace std;
 
int main (){
  string MyString = "Learn C++";
  string::const_iterator cit;

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

  return 0;
}

The output of the above code will be:

L e a r n   C + + 

❮ C++ - String Functions