2015-10-26 27 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

太好了,那会的,谢谢! –