• 0

    posted a message on Function as parameter of a function

     It is possible to pass a function as a parameter to another function in C++. Here is an example of how you can achieve this: Mybkexperience


    #include <iostream>
    #include <functional>

    bool isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }

    void operateOnDateTable(int dates[], int size, std::function<bool(int)> dateJudge) {
    for (int i = 0; i < size; i++) {
    if (dateJudge(dates[i])) {
    std::cout << "Date " << dates[i] << " passes the test." << std::endl;
    } else {
    std::cout << "Date " << dates[i] << " does not pass the test." << std::endl;}}}

    int main() {
    int dates[] = {2000, 2001, 2002, 2003, 2004};
    int size = 5;

    // Pass the isLeapYear function as a parameter to operateOnDateTable
    operateOnDateTable(dates, size, isLeapYear);

    return 0;
    }

    In this example, we define a function isLeapYear that takes an integer argument year and returns a boolean value indicating whether the year is a leap year. We also define a function operateOnDateTable that takes an integer array dates, its size size, and a std::function object dateJudge that represents a function that takes an integer argument and returns a boolean value.

    Inside operateOnDateTable, we loop through the dates array and apply the dateJudge function to each date. If the function returns true, we print a message indicating that the date passes the test; otherwise, we print a message indicating that the date does not pass the test.

    In the main function, we create an integer array dates containing some years, and call operateOnDateTable, passing the dates array, its size, and the isLeapYear function as the dateJudge parameter. This way, the operateOnDateTable function can use the isLeapYear function to judge whether each year in the dates array is a leap year.

    Posted in: Galaxy Scripting
  • To post a comment, please or register a new account.