STD vector code example

Example 1: c++ vector

#include <vector>

int main() {
  std::vector<int> v;
  v.push_back(10); // v = [10];
  v.push_back(20); // v = [10, 20];
  
  v.pop_back(); // v = [10];
  v.push_back(30); // v = [10, 30];
  
  auto it = v.begin();
  int x = *it; // x = 10;
  ++it;
  int y = *it; // y = 30
  ++it;
  bool is_end = it == v.end(); // is_end = true
  
  return 0;
}

Example 2: std vector include c++

#include <vector>
std::vector<std::string> x;

Example 3: vector in c

#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; 
}

Example 4: std vector c++

Vector functions in C++
 --------------------
 clear()  // remove all the elements of the vector container
 insert()  // Inserts new elements before the element at the specified position
 emplace()  // Extends the container by inserting new element at position
 erase()   // Remove elements from a container from the specified position or range
 push_back()  // Push the elements into a vector from the back
 emplace_back() // Constructs an element in-place at the end  
 pop_back()  // Pop or remove elements from a vector from the back   
 resize()  // Changes the number of elements stored     
 swap() // Swap the contents of one vector with another vector of same type. Sizes may differ.

Tags:

Cpp Example