2011-04-19 80 views
2
key_struct kStruct; 
kStruct.x = 2; 
std::find_if(m_cueCommands.begin(), m_cueCommands.end(), find_MyInt(kStruct)); 

struct key_struct 
{ 
    int x; 
    string y; 
    string z; 
} 

struct find_myInt : std::unary_function<key_struct, bool> 
{  
    int x;  
    find_myInt(key_struct kStruct):myInt(kStruct.x){}  
    bool operator()(key_struct const& m) const 
    {   
    return m.x == myInt;  
    } 
}; 

我很確定我有這個有點搞砸了,但是,我認爲它是適度接近。我想要做的是將key_struct作爲我地圖中的關鍵字。我希望能夠搜索密鑰並返回設置key_struct的信息。如果我將key_struct設置爲x = 2,那麼我只想返回int x等於2的地方。如果我設置x = 2和y =「testString」的位置,那麼我只想返回其中x = 2和y =「testString」。C++ STD :: find_if使用結構謂詞

我相信我的方法很接近,但我認爲我錯過了一些東西。想法?

回答

2

你總是想與X比較?或者只有當x!= 0?

順便說一句,您的結構構造函數似乎有錯誤:沒有名爲myInt的成員,因此它應該是:find_myInt(key_struct kStruct) : x(kStruct.x){}。但這並不重要,無論如何都需要改變。

這是我會嘗試。這是未經測試的,可能包含錯誤,布爾返回值的「計算」效率極低。無論如何...

要使用它,創建一個你想要匹配的結構,從代碼中可以看到,它只會嘗試匹配如果x > 0, y != "" and z != ""。因此,如果將「搜索」結構設置爲x = 5, y = "" and z = "",則它將匹配x == 5(可以是任何)的每個密鑰。

typedef std::pair<key_struct, your_value_type> yourMapType; 

struct find_myStruct : std::unary_function<key_struct, bool> 
{ 
    private: 
    key_struct myStruct; 

    public: 
    find_myInt(key_struct const & kStruct): myStruct(kStruct) {} 

    bool operator() (yourMapType const & m) const 
    { 
     bool result = true; 

     if (myStruct.x > 0) 
     result &= (myStruct.x == m.first.x); 

     if (myStruct.y != "") 
     result &= (myStruct.y == m.first.y); 

     if (myStruct.z != "") 
     result &= (myStruct.z == m.first.z); 

     return result; 
    } 
}; 

[編輯]注意到你想使用的地圖,所以我相應地更新代碼。仍然非常未經測試,隨時指出錯誤。

[編輯2]如果您在創建地圖時遇到問題,因爲您的key_struct沒有嚴格的弱順序,那麼應該這樣做。

再次,未經測試,可能包含錯誤。對於所有的if也是非常低效的,但是......你可以隨意用你最喜歡的卡諾圖解算器(BMin想到)解決它們。

struct cmp_key_struct 
{ 
    bool operator() (key_struct const & lhs, key_struct const & rhs) const 
    { 
    bool result = (lhs.x < rhs.x); 

    if ((!result) && (lhs.x == rhs.x)) 
    { 
     result = (lhs.y < rhs.y); 

     if ((!result) && (lhs.y == rhs.y)) 
     result = (lhs.z < rhs.z); 
    } 

    return result; 
    } 
}; 

std::map<key_struct, your_value_type, cmp_key_struct> yourMap; 
0

您不需要在地圖上使用find_if。如果您嘗試將結構用作映射鍵,如您所說,您需要提供「strict weak ordering」的比較。例如,使用「<」而不是「==」。然後將該比較提供給地圖。或者在你的結構中超載<運算符。您可以使用[]運算符或find()方法map執行O(log n)個搜索,其中find_if爲O(n)。

+0

這適用於'binary_search'或'lower_bound',但不適用於執行線性搜索的'std :: find_if'。 – 2011-04-19 13:44:53

+0

'find_if'需要一個等式關係,而不是一個嚴格的弱排序。 – aschepler 2011-04-19 13:46:29

+0

請注意,OP說:「我想要做的是將key_struct作爲我地圖中的關鍵字。」 'map'需要嚴格的弱排序。 – 2011-04-19 13:47:48

0

這是修改後的版本:

struct find_myInt : std::unary_function<key_struct, bool> 
{  
    int myInt;  /// HERE 
    find_myInt(key_struct kStruct):myInt(kStruct.x){}  
    bool operator()(key_struct const& m) const 
    {   
    return m.x == myInt;  
    } 
};