/* * File: Traverse.cpp * ------------------ * This program reimplements the…
- User
/*
- File: Traverse.cpp
-
- This program reimplements the breadth-first search using an
- explicit queue, and depth-first search algorithm using an explicit stack */
#include #include #include #include #include #include #include "CSC3002OJActive/assignment6/simplegraph.h" using namespace std;
void bfs(Node *start) { cout << "Breadth First Search" << endl; if (start == nullptr) return; // check if the start node is valid
set<Node> visitedNodes; queue<Node*> nodeQueue; // Enqueue the starting node on the queue nodeQueue.push(start); while (!nodeQueue.empty()) { // Dequeue the front node from the queue Node* currentNode = nodeQueue.front(); nodeQueue.pop(); // Visit the node if it hasn’t been visited yet if (visitedNodes.find(currentNode) == visitedNodes.end()) { cout << "Visited Node: " << currentNode->name << endl; visitedNodes.insert(currentNode); // Enqueue its neighbors on the queue for (Node* neighbor : currentNode->neighbors) { if (visitedNodes.find(neighbor) == visitedNodes.end()) { nodeQueue.push(neighbor); } } } }}
void dfs(Node *start) { cout<< "Depth First Seacrh"<< endl; if (start == nullptr) return; // check if the start node is valid
set<Node> visitedNodes; stack<Node*> nodeStack; // Push the starting node on the stack nodeStack.push(start); while (!nodeStack.empty()) { // Pop the topmost node from the stack Node* currentNode = nodeStack.top(); nodeStack.pop(); // Visit the node if it hasn’t been visited yet if (visitedNodes.find(currentNode) == visitedNodes.end()) { cout << "Visited Node: " << currentNode->name << endl; visitedNodes.insert(currentNode); // Push its neighbors on the stack for (Node* neighbor : currentNode->neighbors) { if (visitedNodes.find(neighbor) == visitedNodes.end()) { nodeStack.push(neighbor); } } } }}
int main(){ SimpleGraph airline; readGraph(airline, cin); cout << "DFS at Portland ...." << endl; dfs(airline.nodeMap.at("Portland")); cout << "BFS at Portland ...." << endl; bfs(airline.nodeMap.at("Portland")); return 0; } the error is: error: no matching function for call to 'std::set::find(Node*&)'
- Assistant
The error occurs in both the
bfsanddfsfunctions when checking if a node has been visited using thefindfunction of aset<Node>. Thefindfunction expects a const reference to the key type, but in this case, it receives a reference to a pointer to a . To fix this, the set should be declared as a set of pointers to nodes (). The corrected code is as follows:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.