kong kong - 1 year ago 115
C++ Question

How to erase elements from a vector of object?

I know how we can remove elements from a vector of int

std::vector<int> vec;
// .. put in some values ..
int int_to_remove = n;
vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());

What if its a
vector<obj> vec
where obj is

class obj {

int ID;
string name;


How would I remove vectors that are holding onto a certain ID ?

std::vector<obj> vec;
// .. put in some values ..
int id_to_remove = n;
vec.erase(std::remove(vec.ID.begin(), vec.ID.end(), id_to_remove), vec.end());

Answer Source

Now that you are looking to delete objects matching a certain criteria, you need to use std::remove_if instead of std::remove.

    ,   vec.ID.end()
    ,   [](const obj& x) {
            // ID needs to be public in order for this to compile
            return x.ID == id_to_remove;
,   vec.end()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download