簡體   English   中英

在列表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;
}

大概是因為沒有為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM