The reason is that std::map<A,B>::iterator
is a dependent name (in rough terms, it is in a templated function, and depends on A
and B
which are parameters of that template). So it needs to be preceded with the typename
keyword.
template <typename A, typename B>
std::map<B, A> flip_map(std::map<A, B> &src)
{
std::map<B, A> dst;
for (typename std::map<A, B>::iterator it = src.begin(); it != src.end(); ++it)
{
dst.insert(std::pair<B, A>(it->second, it->first));
}
return dst;
}
Additionally you would probably be better specifying src
as const
, and using const_iterator
rather than iterator
, viz
template <typename A, typename B>
std::map<B, A> flip_map(const std::map<A, B> &src)
{
std::map<B, A> dst;
for (typename std::map<A, B>::const_iterator it = src.begin(); it != src.end(); ++it)
{
dst.insert(std::pair<B, A>(it->second, it->first));
}
return dst;
}
or (C++11 and later), let the compiler do the type deduction for you by using auto
and std::make_pair
. This avoids need for the programmer to worry about dependent names.
template <typename A, typename B>
std::map<B, A> flip_map(const std::map<A, B> &src)
{
std::map<B, A> dst;
for (const auto &e : src)
{
dst.insert(std::make_pair(e.second, e.first));
}
return dst;
}