I'm trying to filter a vector so it contains only a specific value.
e.g. Make sure the vector only contains elements of the value "abc."
Right now, I'm trying to achieve this with remove_copy_if
.
Is there any way to pass an additional parameter to a predicate when using one of std's algorithms?
std::vector<std::string> first, second;
first.push_back("abc");
first.push_back("abc");
first.push_back("def");
first.push_back("abd");
first.push_back("cde");
first.push_back("def");
std::remove_copy_if(first.begin(), first.end(), second.begin(), is_invalid);
I'm hoping to pass the following function as a predicate but it seems more likely that this would just end up comparing the current value being examined by remove_copy_if
and the next.
bool is_invalid(const std::string &str, const std::string &wanted)
{
return str.compare(wanted) != 0;
}
I have a feeling I'm probably approaching this wrong so any suggestions would be appreciated!
Thanks
Make functor, or use
std/boost::bind
.Example with bind
Define a functor instead:
or if C++11 use a lambda:
Note that the output vector,
second
, must have elements before the call toremove_copy_if()
:As functor predicates are copied more effort is required to retain the
copied_items
information. See Pass std algos predicates by reference in C++ for suggested solutions.