如何检查for循环内的唯一性? [英] How to check the uniqueness inside a for-loop?

查看:27
本文介绍了如何检查for循环内的唯一性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法检查切片/地图是否存在值?

Is there a way to check slices/maps for the presence of a value?

如果切片中,我想向切片添加一个值.

I would like to add a value to a slice only if it does not exist in the slice.

这有效,但看起来很冗长.有没有更好的方法来做到这一点?

This works, but it seems verbose. Is there a better way to do this?

orgSlice := []int{1, 2, 3}
newSlice := []int{}
newInt := 2
    
newSlice = append(newSlice, newInt)
for _, v := range orgSlice {
    if v != newInt {
        newSlice = append(newSlice, v)
    }
}

newSlice == [2 1 3]

推荐答案

对于每次插入,您的方法将花费线性时间.更好的方法是使用 map[int]struct{}.或者,您也可以使用 map[int]bool 或类似的东西,但空的 struct{} 的优点是它不占用任何额外空间.因此,map[int]struct{} 是一组整数的流行选择.

Your approach would take linear time for each insertion. A better way would be to use a map[int]struct{}. Alternatively, you could also use a map[int]bool or something similar, but the empty struct{} has the advantage that it doesn't occupy any additional space. Therefore map[int]struct{} is a popular choice for a set of integers.

示例:

set := make(map[int]struct{})
set[1] = struct{}{}
set[2] = struct{}{}
set[1] = struct{}{}
// ...

for key := range(set) {
  fmt.Println(key)
}
// each value will be printed only once, in no particular order


// you can use the ,ok idiom to check for existing keys
if _, ok := set[1]; ok {
  fmt.Println("element found")
} else {
  fmt.Println("element not found")
}

这篇关于如何检查for循环内的唯一性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆