【发布时间】:2015-06-16 08:23:09
【问题描述】:
我有一个特定的搜索功能。因为std::set 和std::map 都使用了它,所以它在我们的代码中被复制了(不使用模板)。
我必须维护这两个函数,并且我想使用模板将它们移动到一个函数中(然后只需要维护一个搜索程序)。
我找不到如何将迭代器转换为容器的value_type。对于std::set,您只需要取消引用迭代器(*iter),但对于std::map,您需要访问迭代器的第二项(它是一对)iter->second。
这是一个孤立的例子:
template <class Container, class Object> bool MyFindFunction( const Container& container, Object& found )
{
Container::const_iterator iter = container.begin();
// do my special search procedure here
// note that this code also needs to access the iterator's value...
if ( iter != container.end() )
{
found = *iter; // this works for set, but not for map
found = iter->second; // this works for map, but not for set
// HOW TO MAKE IT WORK FOR BOTH??
return true;
}
else
{
return false;
}
}
int main ()
{
std::set<double> mySet;
std::map<int,double> myMap;
double found = 0;
MyFindFunction( mySet, found );
MyFindFunction( myMap, found );
}
请注意,特殊搜索过程还需要访问 value_type(或 mapped_type 用于映射),因此,将此过程移动到模板函数并具有 MyFindFunctionInMap 和 MyFindFunctionInSet 函数处理迭代器到值调用搜索程序函数后转换无济于事。
PS:对不起,我用的是 C++98..
【问题讨论】:
-
只需使用模板化迭代器创建一个
access函数并为map/set 迭代器实现它。所以你没有完整的功能实现两次,只是有问题的访问 -
迂腐点:
std::map<A, B>的value_type是std::pair<const A, B>,这正是解引用迭代器给你的。您要查找的类型是mapped_type。 -
是的,我正在寻找 mapped_type,它没有为集合定义...这个只有 value_type....
标签: c++ templates dictionary stl set