I was trying to understand functors. I have the below program which I borrowed and modified from functors and their uses.
#include <iostream>
#include <vector>
#include <assert.h>
#include <algorithm>
/*
* A functor is pretty much just a class which defines the operator().
* That lets you create objects which "look like" a function
**/
struct add_x
{
add_x(int y) : x(y)
{
}
int operator()(int y) const {
return x + y;
}
private:
int x;
};
int main()
{
/* create an instance of the functor class*/
add_x add42(42);
/* and "call" it */
int i = add42(8);
/*and it added 42 to its argument*/
assert(i == 50);
/*assume this contains a bunch of values*/
std::vector<int> in;
std::vector<int> out(in.size());
/*
* Pass a functor to std::transform, which calls the functor on every element
* in the input sequence, and stores the result to the output sequence
*/
std::transform(in.begin(), in.end(), out.begin(), add_x(1));
/*for all i*/
assert(out[i] == (in[i] + 1));
return 0;
}
I am getting a segmentation fault in the second assert statement in main(). (assert(out[i] == (in[i] + 1));
)I can't seem to figure out why?