Question

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!

Was it helpful?

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.

OTHER TIPS

I'm pretty sure there isn't a standard function but you can easily write the whole expression using a C++11 lambda:

std::remove_if(myvec.begin(), myvec.end(),
              [&compare_me](std::string const& cmp) -> bool
              {
                return compare_me == cmp;
              });

With compare_me being the "current" string set by the outer loop.

Keep in mind that remove_if returns an iterator to one past the last valid element so in order to get the correct myvec, you have to erase the elements between the iterator returned by remove_if and myvec.end().

For a non-C++11 implementation you'd have to turn the lambda into a function or functor. If you turn it into a functor you can pass the functor directly, if you turn it into a function you'll have to use something like boost::bind to provide the necessary glue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top