clear a vector c++ code example

Example 1: delete from front in vector c++

// Deleting first element
vector_name.erase(vector_name.begin());

// Deleting xth element from start
vector_name.erase(vector_name.begin()+(x-1));

// Deleting from the last
vector_name.pop_back();

Example 2: C++ Vector clear syntax

vector<T>().swap(x);   // clear x reallocating

Example 3: C++ Vector clear

// clearing vectors
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;
  myvector.push_back (100);
  myvector.push_back (200);
  myvector.push_back (300);

  std::cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size(); i++)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  myvector.clear();
  myvector.push_back (1101);
  myvector.push_back (2202);

  std::cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size(); i++)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  return 0;
}

Example 4: clear vs erase vector c++

//Syntax
vectorname.clear()
vectorname.erase(startingposition, endingposition)
  
clear() removes all the elements from a vector container, thus making its 
size 0. All the elements of the vector are removed using clear() function. 
  
erase() function, on the other hand, is used to remove specific elements from 
the container or a range of elements from the container, thus reducing its
size by the number of elements removed.

Tags:

Cpp Example