How can I construct an std::array
with an index sequence, or a lambda which depends on a sequential index?
std::iota
and std::generate
seem relevant, but I'm not sure how to use them to construct an std::array
, rather then apply them on one which is already constructed (which isn't possible in case the element type of the array isn't default-constructible).
Example of the kind of code I'd like to DRY:
#include <array>
class C
{
public:
C(int x, float f) : m_x{x}, m_f{f} {}
private:
int m_x;
float m_f;
};
int main()
{
std::array<int, 10> ar = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::array<C, 3> ar2 = {C{0, 1.0}, C{1, 1.0}, C{2, 1.0}};
return 0;
}
See Question&Answers more detail:os