2013-07-28 32 views
2

對於這個例子,我們取mapstl容器「less」參數如何工作?

我設置地圖對象:map<const char*, int, compare> a,爲compare如下:

struct compare : public std::binary_function<const char*, const char*, bool> 
{ 
    bool operator() (const char* a, const char* b) { 
     return strcmp(a, b) < 0; 
    } 
}; 

有什麼我所做的一切?我是如何超載這個操作員的?那不是一元操作符嗎?

它的工作,但我不知道我真的知道我在這裏寫了什麼。

這是完整的代碼:

#include <set> 
#include <map> 
#include <string> 
#include <iostream> 
using namespace std; 

struct compare : public std::binary_function<const char*, const char*, bool> 
{ 
    bool operator() (const char* a, const char* b) { 
     return strcmp(a, b) < 0; 
    } 
}; 

int main() { 
    map<const char*, int, compare> a; 

    a["Mike"] = 5; 
    a["Tre"] = 3; 
    a["Billie"] = 20; 

    for(map<const char*, int, compare>::iterator it = a.begin(); it != a.end(); ++it) { 
     cout << (*it).first << endl; 
    } 

    cin.get(); 
} 
+0

從技術上講,你的'operator()'成員函數應該標記爲'const'。 –

+0

那些是'std'容器。 'STL'是啓發'std'容器和算法庫的庫的名稱。 – Yakk

回答

2

compare定義允許執行以下操作:

compare cmp; 
bool result = cmp("foo", "bar"); // Two arguments, therefore not unary! 

因此std::map可以用它來確定對元素的相對順序。這是構建二進制搜索樹的必要條件。

+0

這是'map'對象如何使用我的模板參數? – Billie

+1

@ user1798362:粗略地說,是的。通過比較操作,可以構建和搜索二叉搜索樹。 –

+0

好的,現在我明白了。謝謝。 – Billie

1

我在這裏做了什麼?

您創建了一個function object - 一個對象,它提供了operator()的實現,並提供了其類實例化std::map模板。

我是如何超載這個操作符的?

您提供的公共執行(注:struct默認使得其成員public)。

是不是一元運算符?

不是。一個一元運算符需要一個操作數;你的操作符需要兩個操作數,因此是二進制的。