Insertion Ordered Map With Index

Back an insertion-ordered map with a slice of entries plus an index map so set, get and delete stay O(1) while listing order matches insertion.

GoData Integrity

Code

gosnippet
60 lines
package main

import "fmt"

// OrderedMap:entries 存插入顺序,index 提供 O(1) 查找
type OrderedMap struct {
	entries []entry
	index   map[string]int
}
type entry struct { key string; value int }

func NewOrderedMap() *OrderedMap {
	return &OrderedMap{index: make(map[string]int)}
}
func (m *OrderedMap) Set(key string, value int) {
	if i, ok := m.index[key]; ok {
		m.entries[i].value = value // 已存在:原地更新,顺序不变
		return
	}
	m.index[key] = len(m.entries)
	m.entries = append(m.entries, entry{key, value})
}
func (m *OrderedMap) Get(key string) (int, bool) {
	if i, ok := m.index[key]; ok {
		return m.entries[i].value, true
	}
	return 0, false
}
func (m *OrderedMap) Delete(key string) {
	i, ok := m.index[key]
	if !ok {
		return
	}
	// 末位填补空洞:O(1) 删除,末位上移到被删位置
	last := len(m.entries) - 1
	if i != last {
		m.entries[i] = m.entries[last]
		m.index[m.entries[i].key] = i
	}
	m.entries = m.entries[:last]
	delete(m.index, key)
}
func main() {
	m := NewOrderedMap()
	m.Set("zeta", 3)
	m.Set("alpha", 1)
	m.Set("mu", 2)
	m.Set("zeta", 30) // 覆盖不追加,插入序保持
	for _, e := range m.entries {
		fmt.Printf("%s=%d\n", e.key, e.value)
	}
	if v, ok := m.Get("alpha"); ok {
		fmt.Println("alpha:", v)
	}
	m.Delete("alpha")
	fmt.Println("after delete:", len(m.entries), "entries,", len(m.index), "keys")
	for _, e := range m.entries {
		fmt.Printf("%s=%d\n", e.key, e.value)
	}
}

Order of operations

The piece that does the work is the functions NewOrderedMap, Set, Get and Delete — everything else is wiring.

The one repetition in this snippet is the loop for _, e := range m.entries.

Applying it

The main signature reads func NewOrderedMap() *OrderedMap

Running the file prints labeled results such as alpha:, after delete: — each operation’s effect is visible in the output.

The sequence NewOrderedMap, Set, Get and Delete lives in main; running the file triggers it.

Statements that matter

return &OrderedMap{index: make(map[string]int)}
func (m *OrderedMap) Get(key string) (int, bool) {
if i, ok := m.index[key]; ok {
return m.entries[i].value, true
}
return 0, false
}
func (m *OrderedMap) Set(key string, value int) {
if i, ok := m.index[key]; ok {
m.entries[i].value = value // 已存在:原地更新,顺序不变
return
}
m.index[key] = len(m.entries)
m.entries = append(m.entries, entry{key, value})
}

Interactive Tools for This Topic

FAQ

What does Insertion Ordered Map With Index print when run?
Invoke the file as-is — the `alpha:`, `after delete:` prefixes identify which step printed each line.