Answers for "c++ remove class from vector"

C++
0

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;
}
Posted by: Guest on April-20-2021
0

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());
Posted by: Guest on October-06-2020

Code answers related to "c++ remove class from vector"

Browse Popular Code Answers by Language