package main
import (
"fmt"
"sync"
)
// GenericOrderedMap defines a structure for a generic ordered map
type GenericOrderedMap[K comparable, V any] struct {
mu sync.RWMutex
items []struct {
key K
value V
}
}
// NewGenericOrderedMap initializes a new ordered map
func NewGenericOrderedMap[K comparable, V any]() *GenericOrderedMap[K, V] {
return &GenericOrderedMap[K, V]{}
}
// Put inserts the key-value pair into the map
func (m *GenericOrderedMap[K, V]) Put(key K, value V) {
m.mu.Lock()
defer m.mu.Unlock()
m.items = append(m.items, struct {
key K
value V
}{key, value})
}
// Get retrieves the value for a key
func (m *GenericOrderedMap[K, V]) Get(key K) (V, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
for _, item := range m.items {
if item.key == key {
return item.value, true
}
}
var zeroValue V
return zeroValue, false
}
// Main function to demonstrate usage
func main() {
orderedMap := NewGenericOrderedMap[string, int]()
orderedMap.Put("one", 1)
orderedMap.Put("two", 2)
if val, ok := orderedMap.Get("one"); ok {
fmt.Println("Key: one, Value:", val)
}
}
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?