views:

51

answers:

1

I have an array of structures that contain multiple variables:

struct test_case {
    const int input1;
    //...
    const int output;
};

test_case tc[] = {
    {0,  /**/  1},
    //  ...
    {99, /**/ 17}
};

int tc_size = sizeof(tc) / sizeof(*tc);

and I want to extract a vector of the outputs so I can compare them to another array via BOOST_CHECK_EQUAL_COLLECTIONS.

I came up with this:

struct extract_output {
    int operator()(test_t &t) {  
        return t.output;  
    }
}

std::vector<int> output_vector;

std::transform(test_cases, 
               test_cases + tc_size, 
               back_inserter(output_vector), 
               extract_output());

but it seems like I should be able to do this without a functor/struct for each type.

Is there a quicker way to extract a vector/array of one variable from a struct? I tried using boost::lambda, but this didn't work:

std::transform(test_cases, 
               test_cases + tc_size, 
               back_inserter(output_vector), 
               _1.output);

Apparently operator.() cannot be used on lambda variables... what should I use? boost::bind?

+2  A: 

Yes, adding boost::bind is the answer:

std::transform(test_cases, 
               test_cases + tc_size, 
               back_inserter(output_vector), 
               boost::bind(&test_case::output, _1));

This works because std::transform passes in a test_case parameter into the functor generated by bind(). The functor applies the member pointer syntax (&T::x) to extract and return the member variable.

mskfisher
+1, although that's not a member _function_ pointer.
Steve M
Fixed - thanks for catching that.
mskfisher