0

timeInDay我想用尽可能少的行返回我的自定义结构对象数组,以便在我的时间表中返回一天。

struct timeInDay[] getRingTimesForWeekDay(int day) {
  switch (day) {
    case MONDAY:    return { {7, 50} };
    case TUESDAY:   return { {7, 50} };
    case WEDNESDAY: return { {7, 20} };
    case THURSDAY:  return { {7, 50} };
    case FRIDAY:    return { {7, 50} };
    case SATURDAY:  return { {7, 50} };
    case SUNDAY:    return { {7, 50} };
  }
}
struct timeInDay {
  unsigned short hour;
  unsigned short minute;
};

现在它会产生一个带有方法返回值的错误:

error: decomposition declaration cannot be declared with type 'timeInDay'
 struct timeInDay[] getRingTimesForWeekDay(int day) {

如果有人能用尽可能少的行写下他们的做法,将不胜感激。

4

2 回答 2

1

从函数返回 c 数组不需要任何行,因为不能从函数返回 c 数组。

您可以动态分配它并返回指向第一个元素和大小的指针,但您最好远离它,而支持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} };
  }
}

然而,正如其他人已经提到的那样,该函数只返回一个元素,所以不清楚为什么你首先想要一个数组。

PS:如果数组的大小是动态的,使用std::vector

于 2022-01-12T16:52:06.250 回答
1

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;
        }()
    };
于 2022-01-12T17:12:35.477 回答