Really confused by some errors I'm getting related to using a std::map container with a call to std::adjacent_difference. The documentation for adjacent_difference says the following about defining a custom operator:
op - binary operation function object that will be applied.
The signature of the function should be equivalent to the following:
Ret fun(const Type1 &a, const Type2 &b);
The signature does not need to have const &. The types Type1 and Type2 must be such that an object of type iterator_traits::value_type can be implicitly converted to both of them. The type Ret must be such that an object of type OutputIt can be dereferenced and assigned a value of type Ret.
So in the following code (snippet), I have a lambda that returns an integer to a final container to hold the differences between values stored in the map.
std::map<char, int> m;
// Do stuff to initialize map contents here
// ...
std::vector<int> d;
typedef std::pair<char, int> P;
std::adjacent_difference(m.begin(), m.end(), std::back_inserter(d),
[](const P & a, const P & b)->int { return std::abs(a.second - b.second);}
);
And I get some error that is clearly referring to an invalid assignment made between a pair and an integer. Not how I interpreted the documentation, and I'm not sure what I'm missing. I thought the documentation was pretty clear in saying the return value of the lambda is assigned to the result container, but clearly that is not what's happening?
/usr/local/include/c /8.3.0/bits/stl_numeric.h:374:17: error: no match for ‘operator=’ (operand types are ‘std::back_insert_iterator<std::vector<int> >’ and ‘_ValueType’ {aka ‘std::pair<const char, int>’})
*__result = __value;
~~~~~~~~~~^~~~~~~~~
Have I crossed my wires somewhere else?
CodePudding user response:
Studying the cppreference link you provided shows that std::adjacent_difference() cannot transform its output to a type different from the input:
both acc (the accumulated value) and the result of val - acc or op(val, ACC) <...> must be writable to OutputIt.
So, to use algorithms, you would first need to use std::transform() to convert the map into std::vector<int>, and next use std::adjacent_difference(). But a manual loop will probably make more sense.
