我有一个 std::array<Foo, 10>
我想创建一个 std::array<Bar, 10>
使用 Foo
中的函数至Bar
.通常我会使用 std::transform
像这样:
array<Bar, 10> bars;
transform(foos.begin(), foos.end(), bars.begin(), [](Foo foo){
return Bar(foo.m_1, foo.m_2);
});
但是,Bar
没有默认构造函数,所以我无法创建 bars
大批。我总是可以使用 vector
但如果能够使用 array
那就太好了保证我总是有 10 个元素。这可能吗?
最佳答案
std::transform
没有,但没有什么是模板魔法解决不了的。
template<std::size_t N, std::size_t... Is>
std::array<Bar, N> foos_to_bars(const std::array<Foo, N>& foos,
std::index_sequence<Is...>) {
return {{ Bar(foos[Is].m_1, foos[Is].m_2)... }};
}
template<std::size_t N, std::size_t... Is>
std::array<Bar, N> foos_to_bars(const std::array<Foo, N>& foos) {
return foos_to_bars(foos, std::make_index_sequence<N>());
}
std::index_sequence
和 friend 是 C++14,但在 C++11 中很容易实现。仅 SO 就可能有六种实现。
关于c++ - 如何在没有默认构造函数的情况下使用 std::transform 创建 std::array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32175408/