带迭代器的模板函数出错

时间:2016-09-01 13:50:25

标签: c++ templates stl

我想确定向量中的元素是否是其邻居之间的平均值所以我编写了这个程序

#include <iostream>
#include <vector>
using namespace std;

template <typename T>
bool is_avg(vector<T>::iterator x) {         <-- error line
    T l = *(x - 1), m = *x, r = *(x + 1);
    return x * 2 == l + r;
}

int main() {
    vector<int> v;
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    cout << (is_avg(v.begin() + 1) ? "Yes" : "No");
    return 0;
}

但它不起作用

main.cpp|6|error: template declaration of 'bool is_avg'

有什么问题?

1 个答案:

答案 0 :(得分:1)

两件事:首先,您应该使用m * 2代替x * 2,而不能从T推断vector<T>::iterator。而是使用It作为模板参数:

#include <iostream>
#include <vector>
using namespace std;

template <typename It>
bool is_avg(It x) {        // <-- error line
    auto const& l = *(x - 1), m = *x, r = *(x + 1);
    return m * 2 == l + r;
}

int main() {
    vector<int> v;
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    cout << (is_avg(v.begin() + 1) ? "Yes" : "No");
}

Live Example

相关问题