Vector in C++ STL

braindead
2 min readJan 20, 2022

Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inserting at the end takes differential time, as sometimes there may be a need of extending the array. Removing the last element takes only constant time because no resizing happens. Inserting and erasing at the beginning or in the middle is linear in time.

// C++ program to illustrate the
// iterators in vector
#include <iostream>
#include <vector>

using namespace std;

int main()
{
vector<int> g1;

for (int i = 1; i <= 5; i++)
g1.push_back(i);

cout << “Output of begin and end: “;
for (auto i = g1.begin(); i != g1.end(); ++i)
cout << *i << “ “;

cout << “\nOutput of cbegin and cend: “;
for (auto i = g1.cbegin(); i != g1.cend(); ++i)
cout << *i << “ “;

cout << “\nOutput of rbegin and rend: “;
for (auto ir = g1.rbegin(); ir != g1.rend(); ++ir)
cout << *ir << “ “;

cout << “\nOutput of crbegin and crend : “;
for (auto ir = g1.crbegin(); ir != g1.crend(); ++ir)
cout << *ir << “ “;

return 0;
}

Output:

Output of begin and end: 1 2 3 4 5 
Output of cbegin and cend: 1 2 3 4 5
Output of rbegin and rend: 5 4 3 2 1
Output of crbegin and crend : 5 4 3 2 1

--

--

braindead

A passionate programmer, I am eager to challenge myself to do things I’ve never accomplished before and I strive to learn and improve on my skills every day