简体   繁体   English

从结构数组中提取结构成员

[英]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 . 我想提取output的向量,以便可以通过BOOST_CHECK_EQUAL_COLLECTIONS将它们与另一个数组进行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. 但似乎我应该能够在没有每种类型的functor / struct的情况下做到这一点。

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: 我尝试使用boost :: lambda,但这没有用:

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? 显然, operator.()不能用于lambda变量 ...我应该使用什么? boost::bind? 提高::绑定?

Yes, adding boost::bind is the answer: 是的,添加boost :: bind就是答案:

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() . 这是有效的,因为std::transformtest_case参数传递给bind()生成的test_case函数。 The functor applies the member pointer syntax (&T::x) to extract and return the member variable. 仿函数应用成员指针语法(&T::x)来提取并返回成员变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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