如何从Golang中的Slice中删除元素 [英] How to delete an element from a Slice in Golang

查看:105
本文介绍了如何从Golang中的Slice中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  fmt.Println(输入要删除的位置:")fmt.Scanln(& pos)new_arr:= make([] int,(len(arr)-1))k:= 0对于我:= 0;我<(len(arr)-1);{如果i!= pos {new_arr [i] = arr [k]k ++我++} 别的 {k ++}}对于我:= 0;我<(len(arr)-1);我++ {fmt.Println(new_arr [i])} 

我正在使用此命令从切片"中删除元素,但是它不起作用,请提出建议.

解决方案

订单很重要

如果要使数组保持有序,则必须将删除索引右侧的所有元素向左移动一个.希望这可以在Golang中轻松完成:

  func remove(slice [] int,s int)[] int {返回append(slice [:s],slice [s + 1:] ...)} 

但是,这效率不高,因为您可能最终需要移动所有元素,这很昂贵.

顺序并不重要

如果您不关心排序,则可以更快地将要删除的元素与切片末尾的元素交换,然后返回n-1个第一个元素:

  func remove(s [] int,i int)[] int {s [len(s)-1],s [i] = s [i],s [len(s)-1]返回s [:len(s)-1]} 

使用重新分片方法,清空1000000个元素的数组需要224s,而仅花费0.06ns即可.我怀疑在内部,go只会更改切片的长度,而不会对其进行修改.

编辑1

基于以下评论的快速注释(感谢!).

由于目的是删除元素,因此当顺序无关紧要时,只需进行一次交换,第二次将被浪费:

  func remove(s [] int,i int)[] int {s [i] = s [len(s)-1]//我们不需要将s [i]放在最后,因为无论如何它都会被丢弃返回s [:len(s)-1]} 

此外,此答案不执行边界检查.它期望一个有效的索引作为输入.这意味着大于或等于len的负值或索引将导致Go出现恐慌.切片和数组的索引为0,删除数组的第n个元素意味着提供输入 n-1 .要删除第一个元素,请调用 remove(s,0),要删除第二个元素,请调用 remove(s,1),依此类推.>

fmt.Println("Enter position to delete::")
fmt.Scanln(&pos)

new_arr := make([]int, (len(arr) - 1))
k := 0
for i := 0; i < (len(arr) - 1); {
    if i != pos {
        new_arr[i] = arr[k]
        k++
        i++
    } else {
        k++
    }
}

for i := 0; i < (len(arr) - 1); i++ {
    fmt.Println(new_arr[i])
}

I am using this command to delete an element from a Slice but it is not working, please suggest.

解决方案

Order matters

If you want to keep your array ordered, you have to shift all of the elements at the right of the deleting index by one to the left. Hopefully, this can be done easily in Golang:

func remove(slice []int, s int) []int {
    return append(slice[:s], slice[s+1:]...)
}

However, this is inefficient because you may end up with moving all of the elements, which is costy.

Order is not important

If you do not care about ordering, you have the much faster possibility to swap the element to delete with the one at the end of the slice and then return the n-1 first elements:

func remove(s []int, i int) []int {
    s[len(s)-1], s[i] = s[i], s[len(s)-1]
    return s[:len(s)-1]
}

With the reslicing method, emptying an array of 1 000 000 elements take 224s, with this one it takes only 0.06ns. I suspect that internally, go only changes the length of the slice, without modifying it.

Edit 1

Quick notes based on the comments below (thanks to them !).

As the purpose is to delete an element, when the order does not matter a single swap is needed, the second will be wasted :

func remove(s []int, i int) []int {
    s[i] = s[len(s)-1]
    // We do not need to put s[i] at the end, as it will be discarded anyway
    return s[:len(s)-1]
}

Also, this answer does not perform bounds-checking. It expects a valid index as input. This means that negative values or indices that are greater or equal to len(s) will cause Go to panic. Slices and arrays being 0-indexed, removing the n-th element of an array implies to provide input n-1. To remove the first element, call remove(s, 0), to remove the second, call remove(s, 1), and so on and so forth.

这篇关于如何从Golang中的Slice中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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