我正在通过加速C++工作并且遇到Ex的问题.10.2问题涉及从前一章重写中值函数,因此现在可以用向量或内置数组调用中值.中值函数还应允许任何算术类型的容器.
我无法在下面详细说明两次调用中位数 - 我收到错误消息
No matching function for call to 'median'
Run Code Online (Sandbox Code Playgroud)
我从一些研究中得知,当使用模板时,应该在编译时知道Type.这可能是潜在的问题吗?有没有办法以某种方式传递Type作为模板参数?
到目前为止,这是我的代码:
#include <iostream>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <cstddef>
using namespace std;
template <class Iterator, class Type>
Type median(Iterator begin, Iterator end)
{
vector<Type> vec(begin,end);
typedef typename vector<Type>::size_type container_sz;
container_sz size = vec.size();
if (size == 0) {
throw domain_error("median of an empty vector");
}
sort(vec.begin(), vec.end());
container_sz mid = size/2;
return size % 2 == 0 ? (vec[mid] + vec[mid - 1]) / 2 : vec[mid];
}
int main()
{
vector<int> grades;
for (int i = 0; i != 10; ++i){
grades.push_back(i);
}
const int int_array[] = {2, 9, 4, 6, 15};
size_t array_size = sizeof(int_array)/sizeof(*int_array);
cout << median(int_array, int_array + array_size) << endl; //error here: Semantic Issue, No matching function for call to 'median'
cout << median(grades.begin(), grades.end()) << endl; //error here: Semantic Issue, No matching function for call to 'median' "
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您的错误根源在于Type所提供的参数无法进行推导。您可以使用标准库类来执行此操作,iterator_traits如下所示:
template <
class Iterator,
class Type = typename std::iterator_traits<Iterator>::value_type>
Type median(Iterator begin, Iterator end)
{
vector<Type> vec(begin,end);
typedef typename vector<Type>::size_type container_sz;
container_sz size = vec.size();
if (size == 0) {
throw domain_error("median of an empty vector");
}
sort(vec.begin(), vec.end());
container_sz mid = size/2;
return size % 2 == 0 ? (vec[mid] + vec[mid - 1]) / 2 : vec[mid];
}
Run Code Online (Sandbox Code Playgroud)
该类iterator_traits剖析提供的 Iterator 类型以确定它实际迭代的内容(比这稍微复杂一些,但这是一个不错的总结)。有关其工作原理的更多信息,请参阅 的文档class iterator_traits。它是确定迭代器值类型的最方便的机制。
注意:为了确保不会意外绕过默认模板参数Type声明,您还可以执行以下操作:
template <class Iterator>
typename std::iterator_traits<Iterator>::value_type median(Iterator begin, Iterator end)
{
if (begin == end)
throw domain_error("median of an empty vector");
typedef typename std::iterator_traits<Iterator>::value_type Type;
std::vector<Type> vec(begin,end);
sort(vec.begin(), vec.end());
typename std::vector<Type>::size_type mid = vec.size()/2;
return vec.size() % 2 == 0 ? (vec[mid] + vec[mid - 1]) / 2 : vec[mid];
}
Run Code Online (Sandbox Code Playgroud)
它有点密集,并且扔掉了大部分中间内容,但是如果你盯着它看足够长的时间,你就会理解它是如何工作的,并且它会减少你的模板参数列表,只使用你真正关心的一件事;类型Iterator,可以通过您提供给函数的参数简单地推导出来。
| 归档时间: |
|
| 查看次数: |
1156 次 |
| 最近记录: |