2011-03-31 49 views
0

我对库的访问权限有限,所以虽然使用boost :: multi_index可以解决我的问题,但是我不能使用它。C++ STD :: MAP Complex Key Search

我当前的地图设置是: 结构中包含大量的信息,比如INT,我也需要通过它进行搜索。我所希望的是一种结构,例如我可以通过int或string进行搜索并返回结构值。我假设我将不得不写关键,但是,来这里寻求其他建议。

想法?

+0

你基本上给出了答案:自己写。 – 2011-03-31 15:20:58

+2

再次提升有什么问题? – AJG85 2011-03-31 15:27:53

+0

您可以使用std :: pair 并添加您自己的谓词进行搜索。 您可以容纳指向相同对象的两个不同地图。 也许你可以散列字符串和int到一个单一的关键? – ManicQin 2011-03-31 15:28:13

回答

2

我有点困惑。你似乎是说,你有这样的结构:

(psudocode)

struct Gizmo 
{ 
    Gizmo(int foo, string bar) : foo_(foo), bar_(bar) {}; 
    int foo_; 
    string bar_; 
}; 
Gizmo make_gizmo(int foo, string bar) { return Gizmo(foo,bar); } 
std::map<string, Gizmo> my_gizmos; 

my_gizmos["aaa"] = make_gizmo(1,"hello"); 
my_gizmos["bbb"] = make_gizmo(2,"there"); 

...你希望能够通过foo_值来搜索Gizmo S'

在这种情况下,您有两个主要选项。

1)只写仿函数自己定制的(再次psudocude):

struct match_foo : public std::unary_function<...> 
{ 
    match_foo(int foo) : foo_(foo) {}; 
    bool operator()(map<string,Gizmo>::const_iterator it) const 
    { 
    return it->second.foo_ == foo_; 
    } 
private: 
    int foo_; 
}; 

map<string,Gizmo>::const_iterator that = find_if(my_gizmos.begin(), my_gizmos.end(), match_foo(2)); 
}; 

2)创建foo_值的指标,映射回主mapGizmo。该图可能是这个样子 ... 一个

map<int,map<string,Gizmo>::const_iterator> foo_index; 

...你将保持随时更新的主图,my_gizmos

+0

使用迭代器真的很明智吗?当你更新地图时,它们可能会失效。 – ManicQin 2011-03-31 15:55:58

+0

+1:对于选项1 ... @Manic关于需要维护任何时间更新地图的警告是参照它的。 – AJG85 2011-03-31 15:59:05

+0

@ AJG85:啊好吧,我认为他只是想把它添加到地图中并从两张地图上删除。 – ManicQin 2011-03-31 16:04:06

0

如果您的搜索实际上是窗口查询(意味着您必须返回[param0_0,peram0_1] x [param1_0,param1_2] x ...中的值),那么您可以使用范围树结构来提高效率。