2014-03-26 64 views
0

我想了解一個類文件,以便將我自己的書寫代碼與它合併,但是我在理解此模板函數時遇到了一些困難,而且我無法找到這是什麼輸出功能。瞭解此模板功能

template <typename Key, typename Value> struct PriorityItem { 
    Key key; 
    Value value; 
    PriorityItem() {} 
    PriorityItem(Key const& key, Value const& value) : key(key), value(value) { 
    } 
    bool operator<(PriorityItem const& pi) const { 
    if (key == pi.key) 
     return value < pi.value; 
    return key < pi.key; 
    } 
}; 

我可以理解,這個模板得到兩個輸入並初始化它們。那麼如果我沒有認爲它正在成爲某種遞歸函數,但是pi.keypi.value是什麼意思?

它真的是一個遞歸函數嗎?

爲什麼它返回一個比較表格,這是什麼輸出?

+1

'pi'是你比較的'PriorityItem','pi.value'和'pi.key'是它的成員。 'value'和'key'等價於'this-> value'和'this-> key'。 – OMGtechy

+1

一般來說,operator <是爲了使用像std :: set或std :: priority_queue這樣的容器而實現的。我認爲關鍵就像一個名字,這個值用來定義具有相同名字的元素的優先級。 – Caduchon

+1

是的,它不是一個遞歸函數。它不會調用它自己,它返回值爲 Ben

回答

4

它不是一個遞歸函數....

讓我複製和裏面添加註釋:

template <typename Key, typename Value> 
struct PriorityItem { // This is a struct template, it takes two type parameters Key and Value 
    Key key; // Key is an attribute of the struct and is of type Key (one of the template parameters) 
    Value value; // Value is an attribute of the struct and is of type Value (the second template parameter) 
    PriorityItem() {} // This is the default constructor. 
        // It relies on Key and Value types to have proper constructors  
        // in order to initialize the key and value attributes. 
    PriorityItem(Key const& key, Value const& value) : key(key), value(value) { 
        // This is parameter constructor. It provides values 
        // to both attributes and assigns them in the initializer list. 
    } 
    bool operator<(PriorityItem const& pi) const { 
    // This is an operator< method. It allows to do things like : 
    //  PriorityItem<A,B> a; 
    //  PriorityItem<A,B> b; 
    //  ... 
    //  if(a < b) { ... } 
    // 

    // the comparison relationship goes as follows: 
    if (key == pi.key)   // If key attribute is the same in both, PriorityItems... 
     return value < pi.value; // then follow the order of the value attributes. 
    return key < pi.key;  // Otherwise, follow the order of the key attributes. 

    } 
};    

希望這有助於

1

這個類沒有什麼是遞歸的。 PriorityItem(Key const& key, Value const& value)構造函數只是使用與作爲參數傳入的相同值來初始化成員變量。這就是key(key)value(value)的意思。這些是具有相同名稱的memeber變量的構造函數運算符。

1

鍵和值是實例化對象的成員變量。 pi.key和pi.value變量是您用來比較實例化對象的對象。該函數的功能是先比較鍵和鍵是否相同,然後根據它們的值比較對象。