在 List c++ 中查找元素

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;
}

大概是因为没有为测试 class 定义合适的比较运算符==。所以我所做的就是尝试为测试 class 定义 == 运算符,如下所示:

bool operator==(const Testing & lhs, const Testing & rhs) {
    return &lhs == &rhs;
}

仍然没有运气!你能告诉我怎么了吗?我应该如何在该测试对象列表中找到该元素?

非常感谢您的宝贵时间。

您的错误是将 operator== 置于测试 class 中。它应该是一个全局函数。

bool operator==(const Testing & lhs, const Testing & rhs) {
    return &lhs == &rhs;
}

我忽略了你对 operator== 的实际定义,我假设你知道自己在做什么。

首先这个运算符

bool operator==(const Testing & lhs, const Testing & rhs) {
    return &lhs == &rhs;
}

对容器和搜索元素声明为 like

没有意义
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 中定义一些属性并使用它们来比较 class 的对象。在这种情况下,您不应在运算符的主体中使用指针。

例如

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();
}