Arrays compare in golang

huangapple go评论56阅读模式
英文:

Arrays compare in golang

问题

我需要比较两个 uint32 数组,类似这样的代码:

func in(a uint32, list []uint32) bool {
    for _, b := range list {
        if b == a {
            return true
        }
    }
    return false
}

for n := 0; n < len(a); n++ {
    fmt.Println(in(a[n], b))
}
// a 和 b 是 []uint32 类型的数组

但我认为这不是最优的方式。

英文:

I need to compare 2 arrays of uint32, something like this

   func in(a uint32, list []uint32) bool {
    	for _, b := range list {
    		if b == a {
    			return true
    		}
    	}
    	return false
    }
for n := 0 ;n &lt; len(a); n++ {
		fmt.Println(in(a[n], b))
	}
// a and b []uint32

but I think it is not the most optimal way

答案1

得分: 3

如果你实际上使用的是数组,为什么不直接使用==运算符呢?

根据Go语言规范(https://golang.org/ref/spec#Comparison_operators),如果数组元素类型是可比较的,那么数组值就是可比较的。如果两个数组的对应元素相等,那么这两个数组就是相等的。

如果你使用的是切片,可以使用reflect.DeepEqual函数。

但是,根据你的代码,似乎你应该查看一下https://godoc.org/golang.org/x/tools/container/intsets。

然后,你可以创建两个intsets.Sparse,然后进行如下操作:

func main() {
    s1 := intsets.Sparse{}
    s2 := intsets.Sparse{}
    s1.Insert(1)
    s1.Insert(2)
    s1.Insert(3)
    s2.Insert(1)
    s2.Insert(2)
    //s1:{1,2,3}
    //s2:{1,2}
    fmt.Println(s1.SubsetOf(&s2), s2.SubsetOf(&s1))
    //false, true
}

这将忽略重复元素,但会告诉你s1是否是s2的子集,也就是说s1中的每个元素都存在于s2中。

英文:

Why not just use == if you are actually using arrays?

> https://golang.org/ref/spec#Comparison_operators
>
> Array values are comparable if values of the array element type are comparable. Two array values are equal if their corresponding elements are equal.

If you are using slices, you can use reflect.DeepEqual.

But, from your code, it seems like you should look into https://godoc.org/golang.org/x/tools/container/intsets

Then, you create your two intsets.Sparse and could then do:

func main() {
    s1 := intsets.Sparse{}
    s2 := intsets.Sparse{}
    s1.Insert(1)
    s1.Insert(2)
    s1.Insert(3)
    s2.Insert(1)
    s2.Insert(2)
    //s1:{1,2,3}
    //s2:{1,2}
    fmt.Println(s1.SubsetOf(&amp;s2), s2.SubsetOf(&amp;s1))
    //false, true
}

which will ignore duplicates, but let you know if s1 is a subset of s2, meaning every element in s1 exists in s2.

huangapple
  • 本文由 发表于 2017年5月12日 06:53:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/43926833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定