C++ 将作为参数的函数指针传递给另一个函数?

问题描述 投票:0回答:1

我想为图编写广度优先搜索和深度优先搜索函数。但是这些函数应该能够将函数作为参数,这样我就可以将图中的每个节点传递给我在搜索中找到的函数。因为其中一些函数需要自己的参数,所以我如何传递这些辅助参数?

伪代码示例:

void BreadthFirstSearch(node* n, void (*func)(node*)){
     // do the search stuff
     // run the function on each node
     func(current_node);
}
void SetColor(node* n, color c){ // set color... }
void SetNumber(node* n, int i){ //set number... }

int main(){
    // make the graph...
    // set the color...
    BreadthFirstSearch(n, SetColor, WHERE DO I PUT THE COLOR PARAMETER?);

我已经弄清楚如何将函数指针传递给我的搜索函数,但函数指针不需要额外的参数,因此 SetColor(node* n) 可以更改搜索期间给定的每个节点的颜色,但我必须努力将颜色编码到 SetColor 函数中。

这是我的代码的精简版本,以便您可以看到我到目前为止正在尝试的内容:

void BFS(node* n, void (*func)(node*)){
    // make a visited set
    std::set<node*> visited = std::set<node*>();
    // make a frontier queue
    std::queue<node*> frontier = std::queue<node*>();
    frontier.push(n);

    while(!frontier.empty()){
        // get current node from frontier
        node* current = frontier.front();
        frontier.pop();
        // add current node to visited set
        visited.insert(current);
        // get neighbors from current node and add to frontier...
        
        // run the function on the current node
        func(current);
    }
}

void set_color(node* n){
    // hard code the color because I don't know what I'm doing
    n->color = (255, 0, 0);
}

int main(){
    // do stuff
    // run the search with set_color function
    BFS(start_node, set_color);
    // do more stuff
}

我还尝试查找可变参数函数,认为我可以将颜色参数作为额外参数传递。但我对可变参数函数语法的理解不够好。但可能仍然是解决方案的一部分。

c++ function-pointers depth-first-search breadth-first-search function-parameter
1个回答
0
投票

你需要的,和

std::thread
一模一样。

我们可以将函数及其参数传递给

std::thread
的构造函数来创建线程对象。

template< class F, class... Args >
explicit thread( F&& f, Args&&... args );

这是

std::thread
的构造函数的声明。更多详细信息:https://en.cppreference.com/w/cpp/thread/thread/thread

它是关于模板、类型推导和引用折叠的。

这对于新的 C++ 程序员来说可能有点困难。

© www.soinside.com 2019 - 2024. All rights reserved.