This is a creation in Article, where the information may have evolved or changed.
Go Map Introduction
Map in Go is a collection of unordered key-value pairs. The most important point of map is to quickly retrieve the data by key, which is similar to the index, which points to the value of the data. Map is a collection, so we can iterate over it like an iterative algebraic group and a slice. However, map is unordered, and we cannot determine the order in which it is returned because the map is implemented using a chain hash table.
Implementations in C + +
In C + + STL map using red-black tree implementation, you can achieve an orderly map.
Go in the implementation
Implementation principle
The main way to implement this approach is to use space for time. Save the same piece of data through the list and map two data structures. List is used to do sequential traversal, map is used to do the lookup, delete operation
Implementation code
Package Mainimport ("Container/list" "FMT") type Keyer interface {GetKey () String}type maplist struct {Datam AP Map[string]*list. Element dataList *list. List}func newmaplist () *maplist {return &maplist{datamap:make (map[string]*list. Element), Datalist:list. New (),}}func (Maplist *maplist) Exists (data keyer) bool {_, Exists: = maplist.datamap[string (data. GetKey ())] return Exists}func (maplist *maplist) Push (data keyer) bool {if maplist.exists (data) {return FAL SE} elem: = MapList.dataList.PushBack (data) maplist.datamap[data. GetKey ()] = Elem return True}func (maplist *maplist) Remove (data keyer) {if!maplist.exists (data) {return } mapList.dataList.Remove (Maplist.datamap[data. GetKey ()]) Delete (Maplist.datamap, data. GetKey ())}func (maplist *maplist) Size () int {return mapList.dataList.Len ()}func (maplist *maplist) Walk (CB func (data Keyer) {for elem: = MapList.dataList.Front (); Elem! = NIl Elem = Elem. Next () {CB (Elem. Value. (keyer)) }}type Elements struct {value String}func (e Elements) GetKey () string {return E.value}func main () {FMT. PRINTLN ("Starting test ...") ml: = Newmaplist () var A, B, c keyer a = &elements{"Alice"} B = &elements{ "Bob"} c = &elements{"Conrad"} ml. Push (a) ml. Push (b) ml. Push (c) CB: = func (data keyer) {FMT. Println (Ml.datamap[data. GetKey ()]. Value. (*elements).} fmt. Println ("Print elements in the order of pushing:") ml. Walk (CB) FMT. Printf ("Size of maplist:%d \ n", ml.) Size ()) ml. Remove (b) fmt. Println ("After removing B:") ml. Walk (CB) FMT. Printf ("Size of maplist:%d \ n", ml.) Size ())}
Advantages
The complexity of inserting, deleting, and finding the red-black tree is O (logn), and the complexity of this implementation is O (1), which can be said to be a very good data structure.
Disadvantages
Using two data structures, space consumption is a little bit larger. But compared to the tree, the occupancy is not very big.