Open In App
Related Articles

vector :: cbegin() and vector :: cend() in C++ STL

Improve Article
Improve
Save Article
Save
Like Article
Like

Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container.

vector::cbegin()

The function returns an iterator which is used to iterate container.

  • The iterator points to the beginning of the vector.
  • Iterator cannot modify the contents of the vector.

Syntax:

vectorname.cbegin()

Parameters: There is no parameter Return value: Constant random access iterator points to the beginning of the vector. Exception: No exception

Time Complexity – constant O(1)

Below program(s) illustrate the working of the function 

CPP




// CPP program to illustrate
// use of cbegin()
#include <iostream>
#include <string>
#include <vector>
 
using namespace std;
 
int main()
{
    vector<string> vec;
 
    // 5 string are inserted
    vec.push_back("first");
    vec.push_back("second");
    vec.push_back("third");
    vec.push_back("fourth");
    vec.push_back("fifth");
 
    // displaying the contents
    cout << "Contents of the vector:" << endl;
    for (auto itr = vec.cbegin();
         itr != vec.end();
         ++itr)
        cout << *itr << endl;
 
    return 0;
}


Output:

Contents of the vector:
first
second
third
fourth
fifth
vector::cend()

The function returns an iterator which is used to iterate container.

  • The iterator points to past-the-end element of the vector.
  • Iterator cannot modify the contents of the vector.

Syntax:

vectorname.cend()

Parameters: There is no parameter Return value: Constant random access iterator points to past-the-end element of the vector. Exception: No exception

Time Complexity – constant O(1)

Below program(s) illustrate the working of the function 

CPP




// CPP programto illustrate
// functioning of cend()
#include <iostream>
#include <string>
#include <vector>
 
using namespace std;
 
int main()
{
    vector<string> vec;
 
    // 5 string are inserted
    vec.push_back("first");
    vec.push_back("second");
    vec.push_back("third");
    vec.push_back("fourth");
    vec.push_back("fifth");
 
    // displaying the contents
    cout << "Contents of the vector:" << endl;
    for (auto itr = vec.cend() - 1;
         itr >= vec.begin();
         --itr)
        cout << *itr << endl;
 
    return 0;
}


Output:

Contents of the vector:
fifth
fourth
third
second
first

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 09 Jun, 2022
Like Article
Save Article
Previous
Next
Similar Reads