我编写了一个函数,用于查找任何给定容器中最常见的元素(参见下面的代码),其中输入是该容器的两个 const_iterator。findMostFrequent(ivec.begin(), ivec.end())
但是,如果我使用where ivec
is a调用此函数vector<int>
,则编译器无法推断出模板参数。用 with 调用函数可以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;
}