Home  >  Article  >  Backend Development  >  C++ function pointers in action: solving common programming problems

C++ function pointers in action: solving common programming problems

WBOY
WBOYOriginal
2024-04-29 17:33:01841browse

Function pointers provide a powerful way to solve programming challenges in C, including: Comparison functions: Use function pointers to implement custom comparators to facilitate sorting objects. Event handling: Create an event handling system by registering and function pointers that trigger events. Callback function: Transfer control to other functions and restore control at the appropriate time to implement the callback function.

C++ 函数指针实战:解决常见编程难题

C Function Pointer Practice: Solving Common Programming Problems

Function pointers are a powerful function in C, allowing functions to be used as parameters Deliver or store. By understanding the basic concepts and practical applications of function pointers, you can effectively solve various programming challenges.

Basic concepts

A function pointer is a pointer to a function. Its type is a pointer to a function whose return value and parameter types are specified in the pointer declaration. For example:

typedef int (*FuncPtr)(int, int);

This declares a pointer to a function with a return type of int and parameters of int and int.

Practical case

1. Comparison function**

Function pointers can be used to compare two objects. The following code demonstrates how to use a function pointer to implement a custom comparator:

#include <algorithm>

struct Person {
    std::string name;
    int age;
};

// 比较器函数
bool compare_by_name(const Person& lhs, const Person& rhs) {
    return lhs.name < rhs.name;
}

bool compare_by_age(const Person& lhs, const Person& rhs) {
    return lhs.age < rhs.age;
}

int main() {
    std::vector<Person> people = {{"Alice", 30}, {"Bob", 25}, {"Carol", 32}};

    // 使用函数指针对人进行排序
    std::sort(people.begin(), people.end(), compare_by_name);
    for (auto& person : people) {
        std::cout << person.name << std::endl;
    }
    std::cout << std::endl;

    // 使用不同的函数指针对人进行排序
    std::sort(people.begin(), people.end(), compare_by_age);
    for (auto& person : people) {
        std::cout << person.name << std::endl;
    }
    return 0;
}

Output:

Alice
Bob
Carol

Bob
Alice
Carol

2. Event Handling**

Function pointers can be used to create event handling system. The following example shows how to use function pointers to register and trigger events:

#include <map>
#include <functional>

class EventManager {
public:
    // 注册事件
    template<typename Function>
    void Register(const std::string& event, Function callback) {
        callbacks[event].push_back(callback);
    }

    // 触发事件
    void Trigger(const std::string& event) {
        for (auto& callback : callbacks[event]) {
            callback();
        }
    }

private:
    std::map<std::string, std::vector<std::function<void()>>> callbacks;
};

int main() {
    EventManager manager;

    // 注册按钮点击事件
    manager.Register("button_click", []() { std::cout << "Button clicked!" << std::endl; });

    // 模拟按钮点击
    manager.Trigger("button_click");

    return 0;
}

Output:

Button clicked!

3. Callback functions**

Function pointers can be used to implement callback functions, allowing One function transfers control to another function and regains control when appropriate. The following example demonstrates how to create a callback function using a function pointer:

#include <thread>

void Callback(int num) {
    std::cout << "Callback function called with argument: " << num << std::endl;
}

int main() {
    std::thread thread(Callback, 10);
    thread.join();
    return 0;
}

Output:

Callback function called with argument: 10

The above is the detailed content of C++ function pointers in action: solving common programming problems. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn