7

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.

0

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

IMO it is better to write a universal helper functions for such scenarios: godbolt.org/z/TvWaf8Mb1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.