[英]Finding an Element in List c++
我试图在列表中找到一个元素:
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
class Testing {
public:
Testing();
}
list<Testing> Testing_List;
Testing Testing_Object;
auto List_Index = find(Testing_List.begin(), Testing_List.end(), Testing_Object);
它给了我错误信息
Semantic Issue. Invalid Operands to binary expression
template <class _InputIterator, class _Tp>
inline _LIBCPP_INLINE_VISIBILITY
_InputIterator
find(_InputIterator __first, _InputIterator __last, const _Tp& __value_)
{
for (; __first != __last; ++__first)
if (*__first == __value_)
break;
return __first;
}
大概是因为没有为Testing类定义适当的比较操作符==。 因此,我要做的就是尝试为Testing类定义==运算符,如下所示:
bool operator==(const Testing & lhs, const Testing & rhs) {
return &lhs == &rhs;
}
还是没有运气! 你能告诉我怎么了吗? 我应该如何在“测试”对象列表中查找元素?
非常感谢您的宝贵时间。
您的错误是将operator==
放入了Testing类。 它应该是全局函数。
bool operator==(const Testing & lhs, const Testing & rhs) {
return &lhs == &rhs;
}
我忽略了您对operator==
实际定义,我假设您知道自己在做什么。
首先这个运算符
bool operator==(const Testing & lhs, const Testing & rhs) {
return &lhs == &rhs;
}
对于容器和被声明为以下内容的搜索元素没有意义
list<Testing> Testing_List;
Testing Testing_Object;
因为它会将列表中元素的地址与本地变量的地址进行比较,该变量显然对于列表中的所有元素都是不同的。 如果您知道列表中某个元素的地址,则可以使用此运算符。
例如
#include <iostream>
#include <list>
#include <algorithm>
class Testing
{
public:
Testing() = default;
};
bool operator==(const Testing & lhs, const Testing & rhs) {
return &lhs == &rhs;
}
int main()
{
const size_t N = 10;
std::list<Testing> Testing_List;
Testing *sixthElement;
for ( size_t i = 0; i < N; i++ )
{
Testing_List.push_back( Testing() );
if ( i + 1 == 6 ) sixthElement = &Testing_List.back();
}
auto it = std::find( Testing_List.begin(), Testing_List.end(), *sixthElement );
if ( it != Testing_List.end() ) std::cout << "Wow, the sixth element is found!" << std::endl;
else std::cout << "It is the end of the World" << std::endl;
}
程序输出为
Wow, the sixth element is found!
但是,使用这种方法没有太大意义。
您应该在类中定义一些属性,并使用它们来比较类的对象。 在这种情况下,您不应在运算符的主体中使用指针。
例如
class Testing
{
public:
Testing( int i = 0 ) aProperty( i ) {}
int getProperty() const { return aProperty; }
private:
int aProperty;
};
bool operator ==( const Testing &lhs, const Testing &rhs )
{
return lhs.getProperty() == rhs.getProperty();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.