I have a specific search function. Because it's used on both std::set and std::map, it was duplicated in our code (not using template).
I have to maintain those two functions, and I'd like to move them to a single function using a template (and then have only one search preocedure to maintain).
I can't find how to convert an iterator to the container's value_type. For std::set, you just need to dereference the iterator (*iter), but for std::map, you need to access the second item of the iterator (which is a pair) iter->second.
Here is an isolated example:
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 );
}
Note that the special search procedure also needs to access the value_type (or mapped_type for maps), so, moving this procedure to a template function and having a MyFindFunctionInMap and MyFindFunctionInSet function handling iterator to value conversion after calling the search procedure function won't help.
PS: Sorry, I'm using C++98..
accessfunction using the templated iterator and implement it for map/set iterator. So you dont have the complete function implementedtwice, just the problematic accessvalue_typeof astd::map<A, B>isstd::pair<const A, B>, which is exactly what dereferencing an iterator gives you. The type you're looking for ismapped_type.