How to remove element from a vector in C++

Remove elements from vector in C++

In this post, we will see how to remove element from a vector in C++.
There are different methods to remove element in C++ and here we will discuss all of them in detail.
[toc]

Erase() function to remove a single and specific element from a vector

erase() method can be used to remove a single element by passing the position or with the help of index. Here we have discussed all the methods.

Note: When we remove a single element, the iterator passed must be dereferenceable.

Syntax:
For removing a single element:
vector_name.erase(iterator position); //remove using position

Example: vector1 = {10,20,30}, iterator=2
vector.erase(iterator);
Output: 10, 20

We can mark the beginning and ending of the container with the help of begin() and end() functions respectively.

Code:


#include 
#include 
using namespace std;

int main()
{
    vector vector1{ 1, 2, 3, 4, 5, 6, 7,8 };
    vector::iterator it1;

    cout<<"ORIGINAL INTEGER VECTOR ELEMENTS ARE: ";
    for (auto it = vector1.begin(); it != vector1.end(); ++it)
        cout << ' ' << *it;

    //Giving the address of the element to be removed
    it1 = vector1.begin()+1;  
    it1++;//Incrementing by 1

    //Removing the elements with erase() method
    vector1.erase(it1);

    //Printing the vectors after removing elements
    cout<<"\nVECTOR AFTER REMOVAL: ";
    for (auto it = vector1.begin(); it != vector1.end(); ++it)
        cout << ' ' << *it;

    return 0;
}

Output:

ORIGINAL INTEGER VECTOR ELEMENTS ARE: 1 2 3 4 5 6 7 8
VECTOR AFTER REMOVAL: 1 2 4 5 6 7 8

Erase() function to remove a range of elements from a vector

We can also remove a range of elements by passing first and last position in the erase function.

Syntax:
For removing a range of elements:
vector_name.erase(iterator first, iterator last);

Example: vector1={10, 20, 30, 40, 50, 60, 70, 80}, iterator_first=vector1.begin()+1, iterator_last=vector.end()-2

     vector1.erase(iterator_first, iterator_last);

Output: 10, 70, 80

Code:


#include 
#include 
#include 
using namespace std;

int main()
{
    vector vector1{ 1, 2, 3, 4, 5, 7,8 };
    vector vector2 = {"java", "blog", "c++", "python", "code"};
    vector::iterator it1, it2;
    vector :: iterator it_str1, it_str2;

    cout<<"ORIGINAL INTEGER VECTOR ELEMENTS ARE: ";
    for (auto it = vector1.begin(); it != vector1.end(); ++it)
        cout << ' ' << *it;

    cout<<"\nORIGINAL STRING VECTOR ELEMENTS ARE:";
    for (auto it = vector2.begin(); it != vector2.end(); ++it)
        cout << ' ' << *it;

    it1 = vector1.begin()+1;  //Giving the first position of the range
    it2 = vector1.end()-2;  //Marks the end position of the range

    //Marking first and last positions for string vector
    it_str1= vector2.begin()+1;
    it_str2= vector2.end()-2;

    //Removing the elements from the first and last positions.
    vector1.erase(it1, it2);
    vector2.erase(it_str1, it_str2);

    //Printing the vectors after removing elements
    cout<<"\nVECTORS AFTER REMOVAL:\n";
    for (auto it = vector1.begin(); it != vector1.end(); ++it)
        cout << ' ' << *it;
    cout<<"\n";
    for (auto it = vector2.begin(); it != vector2.end(); ++it)
        cout << ' ' << *it;

    return 0;
}

Output:

ORIGINAL INTEGER VECTOR ELEMENTS ARE: 1 2 3 4 5 6 7 8
ORIGINAL STRING VECTOR ELEMENTS ARE: java blog c++ python code
VECTORS AFTER REMOVAL:
1 7 8
java python code

Use erase() and remove_if() methods to remove elements that satisfies the condition

We can use the combination of erase() and remove_if() methods to remove elements that satisfy certain criteria and from a specific range as well.

Note: remove_if method does not elements from container. It shifts all elements to front and provide iterator with the end and then we can use erase to delete those elements.

Code:


#include 
#include 
#include 
using namespace std;

namespace rmv
{
    struct remove
    {
        string key;
        remove(string key): key(key) {}

        bool operator()(string const &i) {
            return i == key;
        }
    };
}

int main() {
    vector vector1;

    //Filling elements in a string vector
    vector1.push_back("Java");
    vector1.push_back("Python");
    vector1.push_back("C++");
    vector1.push_back("Java");
    vector1.push_back("Python");

    // Printing the Original vector
    cout<<"Original Vector is:";
    for (auto it = vector1.begin(); it != vector1.end(); ++it)
        cout << ' ' << *it;

    //removes the element 'java' which appears multiple times in the vector
    vector1.erase(remove_if(vector1.begin(),vector1.end(),rmv::remove("Java")),vector1.end());

    // Printing the vector
    cout<<"\nAfter Removing elements vector is:";
    for (auto it = vector1.begin(); it != vector1.end(); ++it)
        cout << ' ' << *it;
    return 0;
}

Output:

Original Vector is: Java Python C++ Java Python
After Removing elements vector is: Python C++ Python

Use erase() and remove() methods to remove elements that satisfies the condition

We can use the combination of erase() and remove() methods to remove elements that satisfy certain criteria and from a specific range as well. We have to declare an extra header to use remove() method algorithm.

Note: This method cannot be used with the containers that return const_iterator.

Code:


#include 
#include 
#include 
using namespace std;

int main() {
    vector vector1;

    //Filling elements in a string vector
    vector1.push_back("Java");
    vector1.push_back("Python");
    vector1.push_back("C++");
    vector1.push_back("Java");
    vector1.push_back("Python");

    // Printing the Original vector
    cout<<"Original Vector is:";
    for (auto it = vector1.begin(); it != vector1.end(); ++it)
        cout << ' ' << *it;

    //removes the element 'java' which appears multiple times in the vector
    vector1.erase(remove(vector1.begin(),vector1.end(),"Java"),vector1.end());

    // Printing the vector
    cout<<"\nAfter Removing elements vector is:";
    for (auto it = vector1.begin(); it != vector1.end(); ++it)
        cout << ' ' << *it;
    return 0;
}

Output:

Original Vector is: Java Python C++ Java Python
After Removing elements vector is: Python C++ Python

Remove all the elements in the vector using clear() method

We can empty the vector by using the clear() method. No parameters are passed in this function.

Syntax:
For removing all the elements:
vector_name.clear();

Code:


#include 
#include 
using namespace std;

int main()
{
    vector vector1;
    //Filling vector with the values
    vector1.push_back(10);
    vector1.push_back(20);
    vector1.push_back(30);
    vector1.push_back(40);
    vector1.push_back(50);

     // Printing the Original vector
    cout<<"Original Vector is:";
    for (auto it = vector1.begin(); it != vector1.end(); ++it)
     cout << ' ' << *it;

    //Empty the vector
    vector1.clear();

    // Printing the vector
    cout<<"\nAfter emptying:";
    for (auto it = vector1.begin(); it != vector1.end(); ++it)
     cout << ' ' << *it;
    return 0;
}

Output:

Original Vector is: 10 20 30 40 50
After emptying:
//No Output

Conclusion

We discussed different methods to remove a single element or from a range of elements. The time complexity of the erase() method is O(N^2)[because one erase takes linear time] and the clear method is O(N). Any method can be used as per the requirements.

That's all about how to remove element from vector in C++.
Happy Learning!!

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.