如何重载'=='运算符在结构内? [英] How to overload '==' operator within a struct?
问题描述
我有一个结构,我希望使用从一个向量中删除项目,我不知道什么索引项目将出现,所以我删除它的值。这是我的结构:
struct IsUnderScore {
bool operator()(char c){
return c =='_';
}
};
我可以使用这个结构从字符串中删除值,但是当我试图使用一个向量, :
abc.erase(std :: remove(abc.begin(),abc.end(),IsUnderScore()) ,abc.end());
我得到一个编译器错误,说明没有匹配的==运算符。
所以我知道我必须重载这个操作符本身,并且看看一些其他的实现,通过SO,不能真正找到一个匹配我的case,大多数其他版本的实现在其结构中声明了变量,但这是一个简单的bool,看看当前字符是否匹配下划线。
编辑:问题中的向量是一个向量字符串
问题不在于缺少运算符==
,但使用错误的函数+参数对。 remove()
使用项目作为第三个参数,而不是谓语。对于谓词,您需要 remove_if
。所以请执行下列操作之一:
std :: remove(abc.begin(),abc.end )
//或
std :: remove_if(abc.begin(),abc.end(),IsUnderScore())
EDIT
remove
是迭代器值类型的类型。remove_if
中使用的谓词的参数采用相同的类型。根据你的编辑,这是std :: string
在你的情况下,所以你必须相应地使用它。可以使用remove
:std :: remove .begin(),abc.end(),_)
//或
std :: remove(abc.begin ,std :: string(_))
或更新谓词以使用
remove_if
:struct IsUnderScore {
bool operator :: string& s){
return s ==_;
}
};
// ...
std :: remove_if(abc.begin(),abc.end(),IsUnderScore())
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 needremove_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 inremove_if
takes the same type. Based on your edit, this isstd::string
in your case, so you must use it accordingly. Either useremove
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())
这篇关于如何重载'=='运算符在结构内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!