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

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.

Syntax:

vectorname.cbegin()

Parameters:
There is no parameter

Return value:
Constant random access iterator points to the beginning of the vector.



Exception:
No exception

Below program(s) illustrate the working of the function

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}
chevron_right

Output:

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

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

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

Below program(s) illustrate the working of the function

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}
chevron_right

Output:

Contents of the vector:
fifth
fourth
third
second
first

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.





Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :