【发布时间】:2012-07-17 08:27:44
【问题描述】:
我编写了一个函数,用于查找任何给定容器中最常见的元素(参见下面的代码),其中输入是该容器的两个 const_iterator。但是,如果我使用findMostFrequent(ivec.begin(), ivec.end()) 调用此函数,其中ivec 是vector<int>,则编译器无法推断出模板参数。使用findMostFrequent< vector<int> >(ivec.begin(), ivec.end()) 调用函数可以正常工作,但看起来很麻烦。有没有办法让编译器找出要实例化哪个模板?
template <typename T> typename T::value_type findMostFrequent(typename T::const_iterator beg, typename T::const_iterator end)
{
// T is the type of container, T::value_type is the type which is stored in the container
typename T::size_type current_streak = 0, max_streak = 0;
T::value_type max_so_far;
for (T::const_iterator iter = beg; iter != end; ++iter)
{
current_streak = count(beg, end, *iter);
if ( current_streak > max_streak )
{
max_so_far = *iter;
max_streak = current_streak;
}
}
return max_so_far;
}
【问题讨论】:
标签: c++ templates iterator typename