简体   繁体   中英

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());

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

vec.erase(
    std::remove_if(
        vec.ID.begin()
    ,   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()
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM