c++ - (加速 C++)章节管理内存

标签 c++

我正在学习加速的 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/

相关文章:

c++ - 根据 if 语句初始化对象

c++ - 如何将可变参数宏的所有参数连接成带引号的字符串?

c++ - 如何将 "Dummy"值替换为 std::cin?

c++ - 如何通过串行端口发送请求从目录中检索数据?

c# - 使用 WinRT 的 Windows.Graphics.Capture 应用像素着色器

C++ 向后正则表达式搜索

c++ protobuf——我生成的类中的所有方法在哪里?

c++ - QList<T>::operator[] 中的 ASSERT 失败: "index out of range"

c++ - 将对象信息保存到二进制文件中

c++ - gcc reverse_iterator 比较运算符丢失了吗?