Skip to content
Related Articles

Related Articles

Improve Article

deque cbegin() in C++ STL

  • Difficulty Level : Basic
  • Last Updated : 18 Mar, 2019

The cbegin() method in deque is a function in C++ STL which returns an iterator pointing to the first element of the container.

Syntax:

deque_name.cbegin()

Return value: It returns a constant iterator pointing to the first element of the deque. This means, that the iterator can be used to traverse the queue, but not to modify it. That is, functions like insert, erase would throw an error if called using a constant iterator.
The constant iterator should be used when you want no part of your code to modify the contents of the deque.

The following programs illustrates the function.

Program 1:






#include <deque>
#include <iostream>
  
using namespace std;
  
int main()
{
  
    // Create a deque
    deque<int> dq = { 2, 5, 7, 8, 6 };
  
    // Print the first element of deque
    // using cbegin() method
    cout << "First element of the deque is: ";
  
    // Get the iterator pointing to the first element
    // And dereference it
    cout << *dq.cbegin();
}
Output:
First element of the deque is: 2

Program 2:




#include <deque>
#include <iostream>
  
using namespace std;
  
int main()
{
  
    // Create a deque
    deque<int> dq = { 1, 5, 2, 4, 7 };
  
    // Insert an element at the front
    dq.push_front(45);
  
    // Insert an element at the back
    dq.push_back(56);
  
    // Print the first element of deque
    // using cbegin() method
    cout << "First element of the deque is: ";
  
    // Get the iterator pointing to the first element
    // And dereference it
    cout << *dq.cbegin();
}
Output:
First element of the deque is: 45
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :