我想实现一个 ifexists() 模板函数,它检查一个键是否存在于 Map 中 .
如果它是std :: map <>,我可以在模板中使用find()函数,因此可以实现我的模板ifexists()函数 . (下面)
但我使用Boost :: associative_property_map引用我的std :: map . 我可以在这个关联属性映射上使用get和put函数 .
std::map< int, int > mymap;
boost::associative_property_map< std::map< int, int > > asso_map ( mymap );
//asso_map stores reference to mymap. and i can use get and put functions on this associative map.
现在,如果我将此 asso_map 传递给我的模板函数" ifexists( asso_map, key) ",它会抛出以下错误:
error: âclass boost::associative_property_map<std::map<int, int > >â has no member named âendâ
error: âclass boost::associative_property_map<std::map<int, int > >â has no member named âfindâ
这是我的模板功能代码:
template <typename map_t, typename key_t>
bool exists_in(map_t map, key_t key)
{
return map.find(key) != map.end();
}
//function call:--> v is int.
if( exists_in ( asso_map, v) ) ... Error (above)
if( exists_in ( mymap, v) ) ... Correct
它没有成员函数的错误"find"是正确的,在看到文档here之后,很明显它没有find()这样的成员函数 .
但是,如果我将实际 Map (即 mymap )传递给模板功能,它就可以工作 . 但我不想这样做因为那时没有使用boost的关联属性映射的意义 .
我想找到一种方法,我可以使用find()作为我的associative_property_map asso_map . 我知道我可以迭代 assoc_map 然后找到出路 . 但想知道我是否能以某种方式使用find()
我希望它更清楚 . 抱歉模棱两可 .
1 回答
不幸的是,boost::associative_property_map不允许访问它使用的关联容器 . 您无法访问
std::map
的find()
函数,也无法遍历其内容 . 您只能访问Lvalue Property Map的API .