c++ - 使用adjacent_difference编译错误

标签 c++ stl iterator

我正在尝试将 adjacent_difference 与两种不同的迭代器类型一起使用。我创建的仿函数将 InputIterator 使用的类型作为参数,并返回 OutputIterator 使用的类型。我不明白为什么我包含的代码无法编译:

In file included from /usr/include/c++/4.9/numeric:62:0, from 4: /usr/include/c++/4.9/bits/stl_numeric.h: In instantiation of '_OutputIterator std::adjacent_difference(_InputIterator, _InputIterator, _OutputIterator, _BinaryOperation) [with _InputIterator = __gnu_cxx::__normal_iterator >; _OutputIterator = __gnu_cxx::__normal_iterator >; _BinaryOperation = {anonymous}::CheckOp]': 48:85: required from here /usr/include/c++/4.9/bits/stl_numeric.h:374:17: error: cannot convert '_ValueType {aka Test}' to 'float' in assignment *__result = __value;

// Example program
#include <iostream>
#include <string>
#include <numeric>
#include <vector>

struct Test
{
    float first;
    float second;

};

namespace{
    class CheckOp {
    public:

        float operator()(Test x, Test y) const
        {
            float a = x.first - y.first;
            float b = x.second - y.second;

            return a + b;

        }
    };
}

int main()
{
    std::vector<Test> testVec;

    Test test1;
    test1.first = 5.5F;
    test1.second = 6.5F;
    testVec.push_back(test1);
    Test test2;
    test2.first = 2.5F;
    test2.second = 8.5F;
    testVec.push_back(test2);
    Test test3;
    test3.first = 9.4F;
    test3.second = 7.8F;
    testVec.push_back(test3);

    CheckOp checkOP;
    std::vector<float> resultVec(testVec.size());

    std::adjacent_difference(testVec.begin(), testVec.end(), resultVec.begin(), checkOP);


}

最佳答案

注意adjacent_difference的描述(来自cppreference):

First, creates an accumulator acc whose type is InputIt's value type, initializes it with *first, and assigns the result to *d_first.

这意味着输入和输出序列必须具有相同或至少兼容的类型。

关于c++ - 使用adjacent_difference编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43676011/

相关文章:

c# - yield 语句实现

c++ - 如何在 C++ 中从数字排序到字母顺序排序

c++ - 为什么标准不提供通过内容检查来哈希C字符串的特化

python - 如何在C++中使用 "in"关键字

java - For-each 与迭代器。哪个会是更好的选择

java - 是否可以将 Guava 的 ForwardingListIterator 与 PeekingIterator 结合使用?

c++ - 数组程序不能调用bool函数

c++ - 使用 ifstream 读取文件时出错

c++ - 获取图像部分的平均值

c++ - STL 显示输出