std::find没有使用我定义的==运算符
std::find not using my defined == operator
我有一个简单的类,我将它作为指针存储在向量中。我想在向量上使用find,但它找不到我的对象。在调试时,它似乎没有调用我提供的==运算符。我可以在调试器中"看到"对象,这样我就知道它在那里。下面的代码甚至使用了列表中第一项的副本,但仍然失败。我唯一能让它通过的方法是使用MergeLine*mlt=LineList.begin(),这表明它正在比较对象,而根本不使用我的等式运算符。
class MergeLine {
public:
std::string linename;
int StartIndex;
double StartValue;
double FidStart;
int Length;
bool operator < (const MergeLine &ml) const {return FidStart < ml.FidStart;}
bool operator == (const MergeLine &ml) const {
return linename.compare( ml.linename) == 0;}
};
Class OtherClass{
public:
std::vector<MergeLine*>LineList;
std::vector<MergeLine*>::iterator LL_iter;
void DoSomething( std::string linename){
// this is the original version that returned LineList.end()
// MergeLine * mlt
// mlt->linename = linename;
// this version doesn't work either (I thought it would for sure!)
MergeLine *mlt =new MergeLine(*LineList.front());
LL_iter = std::find(LineList.begin(), LineList.end(), mlt);
if (LL_iter == LineList.end()) {
throw(Exception("line not found in LineList : " + mlt->linename));
}
MergeLine * ml = *LL_iter;
}
};
欢呼,Marc
由于容器包含指针而非对象,因此比较将在指针之间进行。指针相等的唯一方法是当它们指向完全相同的对象时。正如您所注意到的,对象本身的比较运算符永远不会被调用。
您可以使用std::find_if
并向其传递一个要使用的比较对象。
class MergeLineCompare
{
MergeLine * m_p;
public:
MergeLineCompare(MergeLine * p) : m_p(p)
{
}
bool operator()(MergeLine * p)
{
return *p == *m_p;
}
};
LL_iter = std::find_if(LineList.begin(), LineList.end(), MergeLineCompare(mlt));
我认为您真正想要的是像这样使用std::find_if
:
struct MergeLineNameCompare
{
std::string seachname;
MergeLineNameComp(const std::string &name) : seachname(name)
{
}
bool operator()(const MergeLine * line)
{
return seachname.compare( line->linename ) == 0;
}
};
LL_iter = std::find_if(LineList.begin(), LineList.end(), MergeLineNameCompare(linename) );
operator ==
(无论哪种形式)都可以更好地保存,以便进行真正的平等比较。
运算符重载不能使用指针,因为它不明确。
Bjarne Stroustrup:-
引入引用主要是为了支持运算符重载。C按值传递每个函数参数,其中传递对象根据值,用户可以传递指针。此策略在运算符过载的情况下不起作用习惯于在这种情况下,符号的便利性是必不可少的,因此用户如果对象是大的
所以,可能不是最好的,但仍然:-
std::vector<MergeLine>LineList;
std::vector<MergeLine>::iterator LL_iter;
相关文章:
- 在 C++ 的自定义运算符中删除与删除[](不同于常见的删除与删除[]问题)
- 自定义运算符重载C++,无开销
- 如何为缺少预定义运算符而不扩展命名空间"std"的标准类型定义运算符>> (istream &, ...)?
- 如何使用C++将MXNET自定义运算符构建到单独的库/包中?
- 模板类的用户定义运算符上的 C++ 隐式转换
- 什么是编程语言支持定义您自己的自定义运算符?
- 如何在Qt中为矩阵类定义[ ][ ]运算符?
- 在 c++ 迭代器中,我应该同时定义运算符== 和运算符!=吗?
- 在 rxcpp 中创建自定义运算符
- 错误 C2676;在C++的二叉搜索树类中定义 ++ 运算符时遇到问题
- std::map :使用自定义运算符时更新密钥
- 最初定义运算符C++在哪里
- 如何在Tensorflow Lite中添加自定义运算符
- 如何在 rxcpp 自定义运算符中正确推断泛型
- 在模板化类之外定义运算符重载
- 为类定义之外的模板类定义运算符[]()(数组订阅)
- 是否可以在类定义之外定义运算符[]()(数组订阅)
- C++ 重新定义运算符<() 和运算符!=()
- 如何将上下文信息传递给自定义运算符<<适用于 std::iostream
- 无法在C++中定义++运算符,这里有什么问题?