Search code examples
c++stringstlremove-if

remove_if string matches a given string in a set


I was thinking about using remove_if on a vector of strings as follows in the pseudo code below:

for(some strings in a given set) {
  remove_if(myvec.begin(), myvec.end(), string_matches_current_string);
}

Now, I am aware I can define the predicate and make this work easily. But I was wondering if there is a standard template function that I could use in place of the predicate above to make this work. I was looking around and couldn't find one. Appreciate any ideas with examples. Thanks!


Solution

  • Why using std::remove_if if you already know the value you want to remove? Use std::remove, which removes the items in the provided range, that match the given value:

    std::vector<std::string>::iterator new_end = my_vec.end();
    for(const auto &current_set_string : some_set)
        new_end = std::remove(myvec.begin(), new_end, current_set_string);
    my_vec.erase(new_end, my_vec.end()); // effectively remove them from the vector.
    

    Note that I used the range-based for loop just to make this shorter, but you should use a regular loop if you can't use C++11.