从结构体数组中提取结构体成员
我有一个包含多个变量的结构数组:
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,添加 boost::bind 就是答案:
这是有效的,因为
std::transform
将test_case
参数传递到bind()
生成的仿函数中代码>.仿函数应用 成员指针语法(& T::x)
提取并返回成员变量。Yes, adding boost::bind is the answer:
This works because
std::transform
passes in atest_case
parameter into the functor generated bybind()
. The functor applies the member pointer syntax(&T::x)
to extract and return the member variable.