c++ remove class from vector code example

Example 1: c++ remove class from vector

#include <algorithm>
#include <vector>
#include <iostream>

class MyClass
{
    public:
    std::string Name;
};

std::vector<MyClass> MyClass_Vector;

int main()
{
    MyClass myclass_1;
    MyClass myclass_2;
    MyClass myclass_3;
    MyClass myclass_4;
    MyClass myclass_5;

    myclass_1.Name = "Name_1";
    myclass_2.Name = "Name_2";
    myclass_3.Name = "Name_3";
    myclass_4.Name = "Name_4";
    myclass_5.Name = "Name_5";

    MyClass_Vector.push_back(myclass_1);
    MyClass_Vector.push_back(myclass_2);
    MyClass_Vector.push_back(myclass_3);
    MyClass_Vector.push_back(myclass_4);
    MyClass_Vector.push_back(myclass_5);

    std::cout << "Before " << MyClass_Vector.size() << "\n";
    for(int i = 0; i < MyClass_Vector.size(); i++) std::cout << MyClass_Vector[i].Name << "\n";

    std::string Name_Of_Class_To_Delete = "Name_2";

    MyClass_Vector.erase(std::remove_if(MyClass_Vector.begin(), MyClass_Vector.end(), [&Name_Of_Class_To_Delete](const MyClass& myclass)->bool
    {
        return myclass.Name == Name_Of_Class_To_Delete;
    }), MyClass_Vector.end());

    std::cout << "\nAfter " << MyClass_Vector.size() << "\n";
    for(int i = 0; i < MyClass_Vector.size(); i++) std::cout << MyClass_Vector[i].Name << "\n";

    return 0;
}

Example 2: vector remove class

carVec.erase(std::remove_if(carVec.begin(), carVec.end(), [&id_to_delete](const Car& ele)->bool
            {
                return ele.getnewId() == id_to_delete;
            }), carVec.end());

Tags:

Cpp Example