【问题标题】:Compile error using adjacent_difference使用相邻差异编译错误
【发布时间】:2017-04-28 08:51:59
【问题描述】:

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

在 /usr/include/c++/4.9/numeric:62:0 包含的文件中, 从 4:/usr/include/c++/4.9/bits/stl_numeric.h:在 '_OutputIterator 的实例化中 std::adjacent_difference(_InputIterator, _InputIterator, _OutputIterator, _BinaryOperation) [with _InputIterator = __gnu_cxx::__normal_iterator >; _OutputIterator = __gnu_cxx::__normal_iterator >; _BinaryOperation = {匿名}::CheckOp]': 48:85:从这里需要 /usr/include/c++/4.9/bits/stl_numeric.h:374:17:错误:无法转换 '_ValueType {aka Test}' 到 'float' 赋值 *__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);


}

【问题讨论】:

  • 您正在尝试将Test 对象分配给floats,因为您正在从vector&lt;Test&gt; 复制到vector&lt;float&gt;。这就是错误消息显示error: cannot convert '_ValueType {aka Test}' to 'float' in assignment *__result = __value; 的原因,您是否期望它起作用? (注意,二进制操作不适用于 first 元素,如果这就是您期望它起作用的原因)。

标签: c++ stl iterator


【解决方案1】:

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

首先,创建一个累加器acc,其类型为InputIt的值类型,用*first对其进行初始化,并将结果赋值给*d_first

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

【讨论】:

  • 这是有道理的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-05
  • 1970-01-01
相关资源
最近更新 更多