2015-10-26 32 views
2

我有一個C++框架,與我的Objective-C(Cocoa)代碼一起使用。我目前實現包裝類來傳遞我的C++對象圍繞obj-C代碼。可可Objective-C:使用c + +對象作爲NSDictionary鍵?

C++對象存儲爲一個層次結構,最近我意識到我需要在obj-C對象和C++對象之間具有一對一的對應關係,因爲我將它們用作NSOutlineView項目,其中a)需要obj-c對象,b)需要精確(即,我需要每次爲相應的C++對象提供相同的obj-c對象)。

我有點卡住最好(即最簡單)的方式來做到這一點。我最好有一個像NSDictionary的東西,在那裏我輸入C++對象作爲一個鍵,並取回相應的obj-c對象。有什麼辦法將C++對象轉換爲唯一的鍵,以便我可以以這種方式使用NSDictionary?或者是否有其他實用的方法來編寫函數以實現類似的目的?

回答

2

是的,當然你可以將任何類對象轉換爲hash的值。下面的代碼演示如何專門的std ::哈希用戶定義類型:

#include <iostream> 
#include <functional> 
#include <string> 

struct S 
{ 
    std::string first_name; 
    std::string last_name; 
}; 

namespace std 
{ 
    template<> 
    struct hash<S> 
    { 
     typedef S argument_type; 
     typedef std::size_t result_type; 

     result_type operator()(argument_type const& s) const 
     { 
      result_type const h1 (std::hash<std::string>()(s.first_name)); 
      result_type const h2 (std::hash<std::string>()(s.last_name)); 
      return h1^(h2 << 1); 
     } 
    }; 
} 

int main() 
{ 
    S s; 
    s.first_name = "Bender"; 
    s.last_name = "Rodriguez"; 
    std::hash<S> hash_fn; 

    std::cout << "hash(s) = " << hash_fn(s) << "\n"; 
} 

一個示例輸出:

散列(S)= 32902390710

這是一個相當高的數目,這使得極少數物體發生碰撞的可能性很小。

reference

+0

太好了,那會的,謝謝! –