gpt4 book ai didi

c++ - 使用adjacent_difference编译错误

转载 作者:行者123 更新时间:2023-11-30 03:32:10 25 4
gpt4 key购买 nike

我正在尝试将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com