c++initializationstdvectorc++23stdarray

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


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.


Solution

  • 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