zoukankan      html  css  js  c++  java
  • go用map实现set

    package main
    
    import "fmt"
    
    func makeSet() *customSet {
        return &customSet{
            container: make(map[string]struct{}),
        }
    }
    
    type customSet struct {
        container map[string]struct{}
    }
    
    func (c *customSet) Exists(key string) bool {
        _, exists := c.container[key]
        return exists
    }
    
    func (c *customSet) Add(key string) {
        c.container[key] = struct{}{}
    }
    
    func (c *customSet) Remove(key string) error {
        _, exists := c.container[key]
        if !exists {
            return fmt.Errorf("Remove Error: Item doesn't exist in set")
        }
        delete(c.container, key)
        return nil
    }
    
    func (c *customSet) Size() int {
        return len(c.container)
    }
    
    func (c *customSet) Print() {
        for k, v := range c.container {
            fmt.Println(k, v)
        }
    }
    
    func main() {
        customSet := makeSet()
        fmt.Printf("Add: A
    ")
        customSet.Add("A")
        fmt.Printf("Add: B
    ")
        customSet.Add("B")
        fmt.Printf("Size: %d
    ", customSet.Size())
        fmt.Printf("C exists? %t
    ", customSet.Exists("C"))
        customSet.Print()
    }
  • 相关阅读:
    POJ3481(待完善版本,请看注释)
    Heap_Sort金老师模板
    poj2255(Tree_Recover)
    快慢指针
    Link_List
    Perl_Tkx_Canvas绘图功能函数介绍
    配置管理
    变更管理
    合同管理
    收尾存在的问题
  • 原文地址:https://www.cnblogs.com/donggongdechen/p/14710652.html
Copyright © 2011-2022 走看看