Open In App

Difference between std::remove and vector::erase for vectors

std::remove : It doesn’t actually delete elements from the container but only shunts non-deleted elements forwards on top of deleted elements.

vector::erase : Removes from the vector either a single element (position) or a range of elements ([first, last)).



std::remove vs vector::erase

std::vector v { 1, 2, 3, 4, 5 };
// remove all elements < 5




// CPP program to illustrate
// difference b/w std::remove
// and std::vector::erase algorithm
#include <bits/stdc++.h>
 
int main()
{
    std::vector<int> vec{ 10, 20, 30, 30, 20, 10, 10, 20 };
    std::vector<int> ve{ 10, 20, 30, 30, 20, 10, 10, 20 };
 
    // Print original vector
    std::cout << "Original vector :";
    for (int i = 0; i < vec.size(); i++)
        std::cout << " " << vec[i];
    std::cout << "\n";
 
    // Iterator that store the position of last element
    std::vector<int>::iterator pend;
 
    // std :: remove function call
    pend = std::remove(vec.begin(), vec.end(), 20);
 
    // Print the vector after std :: remove
    std::cout << "Range contains:";
    for (std::vector<int>::iterator p = vec.begin(); p != pend; ++p)
        std::cout << ' ' << *p; std::cout << '\n';
 
            // Print original vector
            std::cout << "Original Vector :";
    for (int i = 0; i < ve.size(); i++)
        std::cout << " " << ve[i];
    std::cout << "\n";
 
    // std :: vector :: erase function call
    // erase the first 3 elements of vector
    ve.erase(ve.begin(), ve.begin() + 3);
 
    // Print the vector
    std::cout << "Vector contains :";
    for (int i = 0; i < ve.size(); i++)
        std::cout << " " << ve[i];
    std::cout << "\n";
 
    return 0;
}

Output:



Original vector : 10 20 30 30 20 10 10 20
Range contains: 10 30 30 10 10

Original Vector : 10 20 30 30 20 10 10 20
Vector contains : 30 20 10 10 20

Let us see the difference in a tabular form -:

  std::remove vector::erase
1. It is defined in head file <cstdio> It removes single element from the vector.
2.

Its syntax is -:

remove(const char* filename);

Its syntax is -:

iterator erase (const_iterator position);

3. It takes one parameter as filename It returns a random access iterator.
4. It returns 0 if the file is successfully deleted otherwise it returns Non-zero Its time complexity is O(N)

Article Tags :