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

发布于 2024-09-29 23:47:30 字数 1107 浏览 0 评论 0原文

我有一个包含多个变量的结构数组:

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

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

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

我想提取输出的向量,以便我可以通过BOOST_CHECK_EQUAL_COLLECTIONS将它们与另一个数组进行比较。

我想出了这个:

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());

但似乎我应该能够在没有每种类型的函子/结构的情况下做到这一点。

有没有一种更快的方法从结构中提取一个变量的向量/数组?我尝试使用 boost::lambda,但这不起作用:

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

显然 operator.() 不能用于 lambda 变量...我应该使用什么?增强::绑定?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巡山小妖精 2024-10-06 23:47:30

是的,添加 boost::bind 就是答案:

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

这是有效的,因为 std::transformtest_case 参数传递到 bind() 生成的仿函数中代码>.仿函数应用 成员指针语法 (& T::x) 提取并返回成员变量。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文