doubaomao9304 2018-10-08 09:12
浏览 105

如何建立一套?

Given an array of float64 (or any other thing), I would like to build a set similar to the set we find in python. What is the best approach to designing such a data structure?

So far I managed to build a set using a map but it seems awkward to repurpose map to build a set.

package main

import (
    "fmt"
    "sort"
)

func main() {

    var scores = []float64{
        12.0, 6.0, 19.0, 20.0, 2.0, 8.0, 20.0,
    }

    set := make(map[float64]bool)
    for _, t := range scores {
        set[t] = true
    }

    unk := make([]float64, 0, len(set))
    for t := range set {
        unk = append(unk, t)
    }

    sort.Float64s(unk)
    fmt.Println(unk)
}

Will produce

[2 6 8 12 19 20]

  • 写回答

1条回答 默认 最新

  • dongtao1262 2018-10-08 09:50
    关注

    Using a map[float64]bool (or map[float64]struct{}) works well unless you need to have NaNs in the set in which case it will fail.

    Float sets need extra logic to handle the NaN case as NaNs can be used as map indices but do not work as expected.

    You should define your own FloatSet which consists of two fields: One map[float64]struct{} for all "normal" floats (including the Infs) and one hasNaN bool field for NaNs. Insert, Lookup, Remove code need both an extra code path to handle NaNs.

    The "happy" path is perfectly covered by icza's answer but floats always need special treatment for NaNs. (Unless your set will never contain NaNs, until it will contain a NaN and your code will fail with a hard to detect bug.)

    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题