使用非键类型在集中进行有效搜索 [英] Efective search in set with non-key type

查看:124
本文介绍了使用非键类型在集中进行有效搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的数据结构:

struct Data { std::string id; Blob data; };

现在我可以使用 std :: map 存储结构并通过ID搜索,但是我搜索一个方法来实现与 std :: set 相同的事情(因为我真的不需要分离ID和结构)。

Now I can use a std::map to store the structure and search by ID, but I searching for a way to achieve the same thing with a std::set (since I don't really need to separate the ID and the structure).

std :: set :: find 当然采用键类型作为参数,所以我可以这样做(使用适当的构造函数):

std::set::find of course takes the key type as a parameter, so I could do something like this (with the appropriate constructor):

set<Data> x; x.find(Data("some_id"));

但我想避免这种情况。它需要有一个允许ID没有数据的构造函数,加上我不喜欢构造一个对象,只是用它作为搜索的键。

But I would like to avoid this if possible. It would require having a constructor that allows ID without data, plus I don't really like constructing an object, just to use it as a key for search.

问题是:有更好的方法吗?

So my question is: Is there a better way?

推荐答案

除非开销是明显不可接受的,我会去 std :: map< std :: string,Data *> 或者可能 std :: map< std :: string,boost :: shared_ptr< Data> > ,假设您无权访问提供shared_ptr的本地编译器。

Unless the overhead is demonstrably unacceptable I'd go for std::map<std::string, Data *>, or possibly std::map<std::string, boost::shared_ptr<Data> >, assuming you don't have access to a compiler that provides shared_ptr natively.

这篇关于使用非键类型在集中进行有效搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆