search
HomeBackend DevelopmentC++C++ function pointers in action: solving common programming problems

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
How to measure thread performance in C?How to measure thread performance in C?Apr 28, 2025 pm 10:21 PM

Measuring thread performance in C can use the timing tools, performance analysis tools, and custom timers in the standard library. 1. Use the library to measure execution time. 2. Use gprof for performance analysis. The steps include adding the -pg option during compilation, running the program to generate a gmon.out file, and generating a performance report. 3. Use Valgrind's Callgrind module to perform more detailed analysis. The steps include running the program to generate the callgrind.out file and viewing the results using kcachegrind. 4. Custom timers can flexibly measure the execution time of a specific code segment. These methods help to fully understand thread performance and optimize code.

How to use the chrono library in C?How to use the chrono library in C?Apr 28, 2025 pm 10:18 PM

Using the chrono library in C can allow you to control time and time intervals more accurately. Let's explore the charm of this library. C's chrono library is part of the standard library, which provides a modern way to deal with time and time intervals. For programmers who have suffered from time.h and ctime, chrono is undoubtedly a boon. It not only improves the readability and maintainability of the code, but also provides higher accuracy and flexibility. Let's start with the basics. The chrono library mainly includes the following key components: std::chrono::system_clock: represents the system clock, used to obtain the current time. std::chron

What is real-time operating system programming in C?What is real-time operating system programming in C?Apr 28, 2025 pm 10:15 PM

C performs well in real-time operating system (RTOS) programming, providing efficient execution efficiency and precise time management. 1) C Meet the needs of RTOS through direct operation of hardware resources and efficient memory management. 2) Using object-oriented features, C can design a flexible task scheduling system. 3) C supports efficient interrupt processing, but dynamic memory allocation and exception processing must be avoided to ensure real-time. 4) Template programming and inline functions help in performance optimization. 5) In practical applications, C can be used to implement an efficient logging system.

How to process sensor data in C?How to process sensor data in C?Apr 28, 2025 pm 10:00 PM

C is suitable for processing sensor data due to its high performance and low-level control capabilities. Specific steps include: 1. Data collection: Obtain data through the hardware interface. 2. Data analysis: convert the original data into available information. 3. Data processing: filtering and smoothing processing. 4. Data storage: Save data to a file or database. 5. Real-time processing: Ensure the efficient and low latency of the code.

How to use virtual functions in C?How to use virtual functions in C?Apr 28, 2025 pm 09:54 PM

To implement polymorphism using virtual functions in C, you need to declare the function as virtual in the base class and override in the derived class. 1. Declare virtual functions in the base class, such as draw() of the Shape class. 2. Rewrite virtual functions in derived classes, such as draw() of Circle and Rectangle classes. 3. Use virtual destructors to ensure safe deletion of objects. 4. Use override keyword appropriately to avoid errors. 5. Consider pure virtual functions to design interfaces. 6. Pay attention to virtual function analysis in multiple inheritance. The rational use of virtual functions can enable flexible and scalable code, but requires trade-offs on performance overhead and complexity.

How to implement loosely coupled design in C?How to implement loosely coupled design in C?Apr 28, 2025 pm 09:42 PM

To implement loose coupling design in C, you can use the following methods: 1. Use interfaces, such as defining the Logger interface and implementing FileLogger and ConsoleLogger; 2. Dependency injection, such as the DataAccess class receives Database pointers through the constructor; 3. Observer mode, such as the Subject class notifies ConcreteObserver and AnotherObserver. Through these technologies, dependencies between modules can be reduced and code maintainability and flexibility can be improved.

What is exception neutral code in C?What is exception neutral code in C?Apr 28, 2025 pm 09:39 PM

Exception-neutral code refers to a snippet of code that neither throws nor handles exceptions. In C programming, applying exception neutral code can simplify exception handling logic and improve code maintainability and reliability.

How to write a file in C?How to write a file in C?Apr 28, 2025 pm 09:36 PM

Write files in C using the ofstream class. 1) Create ofstream object and open the file. 2) Select the file mode, such as append mode (std::ios::app). 3) Implement error handling and use exception capture. 4) Optimize performance and use buffer management. 5) Use RAII technology to automatically manage file resources.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!