我正在学习加速的 C++,我被困在练习 10.3 中,我什至不知道如何开始。我想在这里提一下,这不是家庭作业,我阅读它只是为了获得对 C++ 的信心。问题如下所示。
Rewrite the median function from §8.1.1/140 so that we can call it with either a vector or a built-in array. The function should allow containers of any arithmetic type.
上面问题的代码如下
template <class T>
T median( vector<T> v)
{
typedef typename vector<T>::size_type vec_sz;
vec_sz size = v.size();
if( size == 0 )
{
throw domain_error(" median of an empty vector");
}
sort( v.begin(), v.end() );
vec_sz mid = size /2;
return size%2 == 0 ? ( v[mid]+v[mid+1])/2 : v[mid] ;
}
我不知道下一步该做什么。任何帮助或批评都会对我有益。 感谢和问候
最佳答案
juanchopanza 和 Mooing Duck 对迭代器的提示的评论可能是本书练习的正确方法。然而,在实际应用中,我可能会编写一个接受数组的包装函数,并调用接受 vector 的原始函数:
template <class T, size_t N>
T median (const T (&a)[N])
{
return median(std::vector<T>(a, a+N));
}
关于c++ - (加速 C++)章节管理内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14970000/