简体   繁体   中英

Extract a struct member from an array of structs

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 output s 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM