реализуй функцию для C++ для создания ориентированного графа из файла
- User
реализуй функцию для C++ для создания ориентированного графа из файла
- Assistant
Я могу предложить следующую реализацию функции для создания ориентированного графа из файла:
#include <iostream> #include <fstream> #include <string> #include <vector> #include <unordered_map> using namespace std; // Ориентированный граф class Graph { public: // Добавление ребра из вершины from в вершину to void addEdge(int from, int to) { adjList[from].push_back(to); } // Вывод графа void printGraph() { for (auto vertex : adjList) { cout << vertex.first << " -> "; for (auto neighbour : vertex.second) { cout << neighbour << " "; } cout << endl; } } private: unordered_map<int, vector<int>> adjList; }; // Функция для создания графа из файла Graph createGraphFromFile(string filename) { ifstream file(filename); Graph graph; if (file.is_open()) { int from, to; while (file >> from >> to) { graph.addEdge(from, to); } } else { cerr << "Error: Unable to open file" << endl; } return graph; } int main() { Graph graph = createGraphFromFile("graph.txt"); graph.printGraph(); return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.