【发布时间】: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<Test>复制到vector<float>。这就是错误消息显示error: cannot convert '_ValueType {aka Test}' to 'float' in assignment *__result = __value;的原因,您是否期望它起作用? (注意,二进制操作不适用于 first 元素,如果这就是您期望它起作用的原因)。