2016-05-25 23 views
-1

的向量上找到,所以我在使用find func在結構向量中找到具有指定相同'char'值的節點時遇到問題。這是我對我的結構代碼,我超載比較運算,但仍然沒有任何運氣不能使用<algorithm>在struct

// STRUCT 
struct alpha 
{ 
    string morse; 
    char letter; 

    // overload the comparison operator 
    bool operator==(const alpha& a) const 
    { 
     return letter == a.letter; 
    } 

}; 

,這裏是

void testFunc(vector<alpha> &vect) 
{ 
    std::vector<alpha>::iterator it; 

    it = find(vect.begin(), vect.end(),'e'); 
    if(it != vect.end()) 
    { 
    // do anything if we ever get here 
    } 
} 

任何幫助將非常感激我的迭代器的代碼,我代碼甚至不會編譯我的錯誤

Invalid operands to binary expression ('alpha' and 'int') 
+0

'bool operator ==(const code&a)const'什麼是'code'? – Chad

+0

你在哪裏定義'code'類型? – Smeeheey

+0

更好的數據結構可以是'std :: map '或散列圖。 – Slava

回答

3

你需要你的結構和炭

bool operator==(const char c) const 
    { 
     return letter == c; 
    } 
+0

你真了不起! –

+0

'std :: find() ''保證'value'將在表達式的右邊? – Slava

+0

是的函數使用operator ==比較單個元素與val –

0

std::find不能隱式char轉換爲alpha。您需要提供將執行該轉換的構造函數,或者將您創建的對象提供給find函數,或者添加另一個operator==函數,該函數將與char進行比較。

另外,您定義的 operator==函數與 code對象進行比較?這應該是正確的嗎?

+0

謝謝隊友,修正了「bool operator ==(const alpha&a)const」仍然有相同的錯誤,雖然:( –

+0

他說你需要提供ctor類型爲'char'的單參數,可以用於類型轉換。 – Slava

+1

如果您的答案中有錯誤或無關緊要的信息,請將其刪除。我沒有看到將它留下,而是通過它觸及一條線。 –

-1
bool operator==(const alpha& a) const 
{ 
    return letter == a.letter; 
} 
0

find(vect.begin(), vect.end(),'e');之間定義相等運算的find第三個參數是不是一個alpha對象。你應該constuct這樣一個對象中預先:

alpha eKey; 
eKey.letter='e'; 
vector<alpha>::iterator it = find(vect.begin(), vect.end(), eKey); 

這將使propper使用find功能。