cend() Function in C++
Last Updated :
27 Nov, 2022
Cend() is the function defined in C++ STL. This function produces a constant random access iterator that identifies the deque’s past-the-end element. If the container is empty then cend() function returns the same as cbegin() function. This member function’s iterator can only be used to iterate containers; it cannot be used to change the content of the object it is pointing at.
Syntax:
const_iterator cend() const noexcept;
A const_iterator is an iterator that points to constant content.
Example 1: Below is the C program to use cend() function in deque to print elements in reverse order:
C++
#include <iostream>
#include <deque>
using namespace std;
int main()
{
deque< int > d = {1, 2, 3, 4, 5};
cout << "Elements of deque in reverse order: " <<
endl;
for ( auto it = d.cend() - 1;
it >= d.cbegin(); --it)
cout << *it << " " ;
cout << endl;
return 0;
}
|
Output
Elements of deque in reverse order:
5 4 3 2 1
- Time Complexity: O(n) where n is the number of elements in the deque.
- Auxiliary Space: O(1)
Example 2: Below is the C program to use cend() function in deque to print elements of deque:
C++
#include <iostream>
#include <deque>
using namespace std;
int main()
{
deque<string> d = { "geeks" , "for" , "geeks" };
auto itr = d.cbegin();
while (itr != d.cend())
{
cout << *itr;
cout << " " ;
++itr;
}
return 0;
}
|
- Time Complexity: O(n) where n is the number of elements in the deque.
- Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...