如何将元素中的数据分组为元组向量
我想将元素中的元素数据分组为室内的元组。 给定的是包含数据的元组元组。有多种重复类型,该数据应分组为每种唯一类型的向量。
到目前为止 boost :: mp11
是我发现的最优雅的方式
std :: tuple< std :: vector< t1>,std :: tuple< std :: vector< t2>,...>
基于传入参数包
std :: tuple< std :: tuple< some_data>,std :: tuple&lt< std :: tuple< some_more_more_data>,...
使用 mp_unique
和 mp_transform
获取每种唯一类型的向量。
如果您知道 std ::
ish替代方案(可选),请开心。
我被困在寻找一种将元组元素填充到匹配矢量中的方法吗? 我很兴奋,找到一种折叠的表达方式。
这个示例应该有助于更好地了解我的想法。
template <typename T> using vector_of = std::vector<T>;
static constexpr auto tuple_to_vector(auto&&... Vs) noexcept {
// merged_tuple = std::tuple<int, double, int, char, int, float, char, float, double>
auto merged_tuple = std::tuple_cat(std::forward<decltype(Vs)>(Vs)...);
// vector_t = std::tuple<std::vector<int>, std::vector<double>, std::vector<char>, std::vector<float>>
using vector_t = boost::mp11::mp_transform<vector_of, boost::mp11::mp_unique<decltype(merged_tuple)>>;
vector_t vec;
// how to add merged_tuple elements to vec
// resulting in
// std::tuple< std::vector<int>{1,3,2}, std::vector<double>{2.0,3.0}, std::vector<char>{'b','c'}, std::vector<float>{3.0f,2.0f}>
return std::move(vec);
};
int main() {
constexpr auto vec = tuple_to_vector(
std::make_tuple(1,2.0,3),
std::make_tuple('b',2,3.0f),
std::make_tuple('c',2.0f,3.0)
);
// expecting
// vec = std::tuple<
// std::vector<int>{1,3,2},
// std::vector<double>{2.0,3.0},
// std::vector<char>{'b','c'},
// std::vector<float>{3.0f,2.0f}
// >
return 42;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
std :: apply
MERGED_TUPLE
的元素,并使用std :: get
根据该类型提取相应的vector
在vector_t
中根据该类型该元素的内容,然后通过vector
通过push_back
demo
请注意,
vec
不能constexpr
即使在C ++ 20中,由于其分配是非传播的。如果您真的想构造constexpr
元组,则可以使用std ::数组
,因为可以在编译时获得数组的大小。这是 demo 将结果转换为相应的vec
std ::数组类型。You can use
std::apply
to expand the elements ofmerged_tuple
, and usestd::get
to extract the correspondingvector
invector_t
according to the type of the element, and fill into thevector
throughpush_back
Demo
Note that
vec
cannot beconstexpr
even in C++20 since its allocation is non-transient. If you really want to construct aconstexpr
tuple, then you can usestd::array
since the size of the array can be obtained at compile time. Here is a demo that converts the resultingvec
to the correspondingstd::array
type.