Thought it was pretty straight forward.
But I get a “iterator not dereferencable” errro when running the below code.
What’s wrong?
template<typename T>
struct SumsTo : public std::binary_function<T, T, bool>
{
int myInt;
SumsTo(int a)
{
myInt = a;
}
bool operator()(const T& l, const T& r)
{
cout << l << " + " << r;
if ((l + r) == myInt)
{
cout << " does add to " << myInt;
}
else
{
cout << " DOES NOT add to " << myInt;
}
return true;
}
};
void main()
{
list<int> l1;
l1.push_back(1);
l1.push_back(2);
l1.push_back(3);
l1.push_back(4);
list<int> l2;
l2.push_back(9);
l2.push_back(8);
l2.push_back(7);
l2.push_back(6);
transform(l1.begin(), l1.end(), l2.begin(), l2.end(), SumsTo<int>(10) );
}
Your functor is fine. The problem is in the call to
transform.Transform has the prototype
your call is
instead of
l2.end(), the fourth iterator argument needs to be the beginning of the result sequence. It should reference a sequence of objects that you can construct frombool.If you want to save the results into
l2, then you wantAs GMan suggests, another approach is
std::back_inserterfrom<iterator>: