Return an array which is iniated in a one liner
No line is required to return a c-array from a function, because you cannot return a c-array from a function.
You could dynamically allocate it and return a pointer to first element and size, but you better stay away from that in favor of std::array
:
#include <array>
struct timeInDay {
unsigned short hour;
unsigned short minute;
};
std::array<timeInDay,1> getRingTimesForWeekDay(int day) {
switch (day) {
case 1: return { {7, 50} };
default: return { {7, 50} };
}
}
However, as others have mentioned already, the function does only return a single element, so it isnt clear why you want an array in the first place.
PS: If the size of the array is dynamic, use std::vector
Your getRingTimesForWeekDay
just returns a timeInDay
struct object. If you want to have an array of timeInDay
structs, you can just define it:
[Demo]
std::array<timeInDay, num_week_days> ringTimesForWeekDays{
{{7, 50}, {7, 50}, {7, 20}, {7, 50}, {7, 50}, {7, 50}, {7, 50}}
};
If you want to be able to regenerate the contents of the array by code later on, you can keep the getRingTimesForWeekDay
function, and use it to fill the array:
[Demo]
std::generate(std::begin(ringTimesForWeekDays), std::end(ringTimesForWeekDays),
[d = DayOfWeek::MONDAY]() mutable {
auto t{ getRingTimesForWeekDay(d) };
d = static_cast<DayOfWeek>(static_cast<int>(d) + 1);
return t;
});
Also, you could initialize your array at compile time with the results of an immediately invoked lambda expression:
[Demo]
constexpr auto ringTimesForWeekDays{
[](){
std::array<timeInDay, num_week_days> result{};
std::generate(std::begin(result), std::end(result), [d = DayOfWeek::MONDAY]() mutable {
auto t{ getRingTimesForWeekDay(d) };
d = static_cast<DayOfWeek>(static_cast<int>(d) + 1);
return t;
});
return result;
}()
};