std::string::crbegin() and std::string::crend() in C++ with Examples
std::string::crbegin()
The std::string::crbegin() is a string class built-in function that returns a constant reverse iterator referring to the last element in the string. Using this iterator starts the string traversal from the end of the string. Header File:
#include <string>
Template Class:
template <class C>
auto crbegin( const C& c )
-> decltype(std::rbegin(c));
Syntax:
string_name.crbegin()
Parameters: This function doesn’t require any parameters. Return Value: This function std::string::crbegin() returns a constant reverse iterator referring to the last element in the string. Below is the program to illustrate string::crbegin(): Program 1:
CPP
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str( "GeeksForGeeks" );
for ( auto it = str.crbegin();
it != str.crend(); it++) {
cout << *it;
}
return 0;
}
|
Time Complexity: O(N) // Where N is the length of the string.
Auxiliary Space: O(1)
std::string::crend()
The std::string::crend() is a string class built-in function that returns a constant reverse iterator pointing to the theoretical element before the first element in the string. This iterator is used to reach the starting of the string while traversing the string in reverse order. Template Class:
template <class C>
auto crend( const C& c )
-> decltype(std::rend(c));
Syntax:
string_name.crend()
Parameters: This function doesn’t require any parameters. Return Value: This function std::string::crend() returns a constant reverse iterator pointing to the element before the first element in the string. Below is the program to illustrate string::crend(): Program 2:
CPP
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str( "GeeksForGeeks" );
int N = str.length();
char ch = 'k' ;
bool a = true ;
for ( auto it = str.crbegin();
it != str.crend(); it++) {
if (*it == ch) {
cout << "The last index is "
<< N - (it - str.crbegin() + 1)
<< endl;
a = false ;
break ;
}
}
if (a) {
cout << "Character is not present" ;
}
return 0;
}
|
Output:
The last index is 11
Time Complexity: O(N) // Where N is the length of the string.
Auxiliary Space: O(1)
Let us see the differences in a tabular form -:
|
std::string::crbegin() |
std::string::crend() |
1. |
It is used to return a const_reverse_iterator pointing to the last character of the string |
It is used to return a const_reverse_iterator pointing to the theoretical character preceding the first character of the string |
2. |
Its syntax is -:
const_reverse_iterator crbegin()
|
Its syntax is -:
const_reverse_iterator crend();
|
3. |
It does not take any parameters. |
It does not take any parameters. |
4. |
Its complexity is constant. |
Its complexity is constant. |
5. |
Its iterator validity does not changes. |
Its iterator validity does not changes. |
Last Updated :
10 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...