Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directly initialize std::array with a fixed count of elements from std::vector [duplicate]

The elements in the array are not default constructible therefore we need to initialize the array directly from elements in std::vector.

#include <array>
#include <vector>

class foo {
public:
  foo(int i, float j) : i{i}, j{j} {}

private:
  int i;
  float j;
};

void bar() {
  std::vector<foo> baz = {{0, 1}, {0, 2}, {0, 3}};
  constexpr size_t copyCount = 2;
  std::array<foo, copyCount> copiedElements =
      /* somehow initilize this to the copyCount elements from baz */;
}

An elegant and simple solution would be preferred.

like image 667
sentientbottleofwine Avatar asked Jul 26 '26 01:07

sentientbottleofwine


1 Answers

You can use a template lambda whose template argument is an integer sequence Is; this sequence can then be used in order to get a value of baz at a given index.

auto copiedElements = [&] <std::size_t...Is> (std::index_sequence<Is...>) {
    return std::array<foo, copyCount> {{baz[Is]... }};
} (std::make_index_sequence<copyCount>{} );

Demo

like image 86
abcdefg Avatar answered Jul 28 '26 15:07

abcdefg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!