I have a struct which I wish to use to remove items from a vector, I do not know what index the item will appear at so I'm removing it by value. Here is my struct:
struct IsUnderScore{
bool operator()(char c){
return c=='_';
}
};
I can use this struct to remove values from strings but when I try to use on a vector like so:
abc.erase(std::remove(abc.begin(), abc.end(), IsUnderScore()), abc.end());
I get a compiler error saying there is no match for the == operator.
So I know I have to overload this operator itself, and in looking at some of the other implementations of it throughout SO, can't really find an implementation that matches my case, most other versions have variables declared in their structs but this is a simple bool to see if the current character matches underscore. I'm kind of confused as how I should build my overload to match my case.
EDIT: The vector in question is a vector string by the way.
The problem is not with a missing operator==
, but with using the wrong function+argument pair. remove()
takes an item as the 3rd argument, not a predicate. For a predicate, you need remove_if
. So do one of these:
std::remove(abc.begin(), abc.end(), '_')
// or
std::remove_if(abc.begin(), abc.end(), IsUnderScore())
EDIT
The 3rd parameter of remove
is of the type of the iterator's value type. The parameter of the predicate used in remove_if
takes the same type. Based on your edit, this is std::string
in your case, so you must use it accordingly. Either use remove
with a string:
std::remove(abc.begin(), abc.end(), "_")
// or
std::remove(abc.begin(), abc.end(), std::string("_"))
Or update the predicate for use with remove_if
:
struct IsUnderScore{
bool operator()(const std::string &s){
return s == "_";
}
};
// ...
std::remove_if(abc.begin(), abc.end(), IsUnderScore())
You use std::remove
- it does not use the comparator as the third argument, but just the value to remove. Assuming that your abc
vector is vector<char>
use
std::remove(abc.begin(), abc.end(), '_')
You are trying remove
instead remove_if
. (Or you are trying remove
with a functor, instead a char).
The best and simple solution:
abc.erase(std::remove(abc.begin(), abc.end(), '_'), abc.end());
The alternative (not too useful here, but just in case you need a more complex comparison to determine what element to remove):
abc.erase_if(std::remove_if(abc.begin(), abc.end(), IsUnderScore()), abc.end());