-1

I have a function which accepts std::array by const reference and processes its elements

void foo(const std::array<int,10> &arr) {
    // do some stuff
}

I would like to pass this array all filled with some custom value (say, 5), so array becomes {5, 5, 5, ...}.

In my code I can create an array, fill it with fill(5) method and then pass to a function

std::array<int,10> arr;
arr.fill(5);
foo(arr);

Is there any way to fill array inside function arguments so the final result will be like that:

foo(std::array<int,10>(5));

?

I know, that std::vector have such a constructor, but it doesn't match my case.

elo
  • 489
  • 3
  • 13

1 Answers1

-1

std::array is an aggregate, so it works with aggregate initialization.

#include <array>

void foo(const std::array<int,10> &arr) {
    // do some stuff
}

int main() {
    foo(std::array<int,10>{5,5,5,5,5,5,5,5,5,5});
}

If you want something that scales better you can make a function that returns an array of the right size.

#include <array>
#include <iostream>

void foo(const std::array<int,10> &arr) {
    for (auto v : arr) {
        std::cout << v << ' ';
    }
}

template <typename T, std::size_t... I>
constexpr std::array<T, sizeof...(I)> make_filled_arr_impl(T t, std::index_sequence<I...>) {
    return {(I, t)...};
}

template <std::size_t Size, typename T>
constexpr std::array<T, Size> make_filled_arr(T t) {
    return make_filled_arr_impl(t, std::make_index_sequence<Size>{});
}

int main() {
    foo(make_filled_arr<10>(5));
}
super
  • 12,335
  • 2
  • 19
  • 29
  • Not the downvoter but I assume it got DV'd because OP is looking for a more clean example, to cut out the aggregate completely. – Hatted Rooster Jul 19 '21 at 12:26
  • 1
    They didn't explicitly say it, but I assume nobody wants to repeat the number N times. – HolyBlackCat Jul 19 '21 at 12:26
  • This solution doesn't scale. If the array had a sized of 1000, they aren't going to use aggregate intialization. – NathanOliver Jul 19 '21 at 12:28
  • @NathanOliver yet the solution answers OP's question, does it not? OP never asked for a scalable solution... – SergeyA Jul 19 '21 at 12:43
  • @SergeyA The OP asks for something like `foo(std::array(5));`. To me, that means the `5` should only be specified once, not N times. – NathanOliver Jul 19 '21 at 12:46
  • @NathanOliver Answerer added function solution, so this discussion is moot. I still would not downvote even in the original form, though. – SergeyA Jul 19 '21 at 12:48