In Go, you can create a generic graph structure using maps and slices. A graph can represent various types of data relationships through its nodes and edges. Below is an example of how to implement a simple generic graph structure in Go.
package main
import "fmt"
// Graph represents a generic graph structure
type Graph[T any] struct {
vertices map[T]bool
edges map[T]map[T]bool
}
// NewGraph creates a new graph
func NewGraph[T any]() *Graph[T] {
return &Graph[T]{
vertices: make(map[T]bool),
edges: make(map[T]map[T]bool),
}
}
// AddVertex adds a vertex to the graph
func (g *Graph[T]) AddVertex(vertex T) {
if !g.vertices[vertex] {
g.vertices[vertex] = true
g.edges[vertex] = make(map[T]bool)
}
}
// AddEdge adds an edge between two vertices in the graph
func (g *Graph[T]) AddEdge(v1, v2 T) {
if g.vertices[v1] && g.vertices[v2] {
g.edges[v1][v2] = true
g.edges[v2][v1] = true // For undirected graph
}
}
// Display prints the graph
func (g *Graph[T]) Display() {
for vertex := range g.vertices {
fmt.Print(vertex, ": ")
for neighbor := range g.edges[vertex] {
fmt.Print(neighbor, " ")
}
fmt.Println()
}
}
func main() {
graph := NewGraph[int]()
graph.AddVertex(1)
graph.AddVertex(2)
graph.AddVertex(3)
graph.AddEdge(1, 2)
graph.AddEdge(2, 3)
graph.Display()
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?