push_front vector c++ code example

Example 1: inserting at start in vector c++

// Inserting at start
vector_name.insert(vector_name.begin(), element_to_be_inserted);

// Inserting after xth element
vector_name.insert(vector_name.begin()+(x-1), element_to_be_inserted);

// Inserting at last
vector_name.push_back(element_to_be_inserted);

Example 2: 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 3: insert at position in vector c++

// where v is the vector to insert, i is
// the position, and value is the value

v.insert(v.begin() + i, v2[i])

Example 4: vector push front insert()

auto it = vec.insert(vec.begin(), 3);

Tags:

Cpp Example