gpt4 book ai didi

c++ - cocoa Objective-C : use c++ objects as NSDictionary keys?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:48:41 24 4
gpt4 key购买 nike

我有一个与我的 Objective-C (Cocoa) 代码一起使用的 C++ 框架。我目前实现包装器类以围绕 obj-C 代码传递我的 C++ 对象。

C++ 对象存储为层次结构,而且,我最近意识到我需要在 obj-C 对象和 C++ 对象之间建立一对一的对应关系,因为我将它们用作 NSOutlineView项,a) 需要是 obj-c 对象,b) 需要精确(即,我每次都需要为相应的 c++ 对象提供相同的 obj-c 对象)。

我对执行此操作的最佳(即最简单)方法有点困惑。理想情况下,我会拥有类似 NSDictionary 的东西,我在其中输入 c++ 对象作为键,然后取回相应的 obj-c 对象。有什么方法可以将 C++ 对象转换为 unique 键,以便我可以以这种方式使用 NSDictionary 吗?或者有没有其他实用的方法来编写一个函数来实现类似的目的?

最佳答案

是的,当然你可以将任何类对象转换成hash值。下面的代码演示了如何将 std::hash 专门化为用户定义的类型:

#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";
}

示例输出:

哈希 = 32902390710

这是一个相当高的数字,这使得相对较少的对象极不可能发生碰撞。

reference .

关于c++ - cocoa Objective-C : use c++ objects as NSDictionary keys?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33354349/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com