arrays - 从数组中删除项目

标签 arrays vb6

如何删除数组中间的项目?我试过这个:

Public Sub RemoveArrayElement(AryVar() As Object, ByVal RemoveWhich As Long)
Dim byteLen As Byte    
byteLen = 4

If RemoveWhich < UBound(AryVar) Then
    CopyMemory ByVal VarPtr(AryVar(RemoveWhich)), ByVal _
        VarPtr(AryVar(RemoveWhich + 1)), (byteLen) * _
        (UBound(AryVar) - RemoveWhich)
End If

If UBound(AryVar) = LBound(AryVar) Then
    Erase AryVar
Else
    ReDim Preserve AryVar(UBound(AryVar) - 1)
End If
End Sub

但是当我从 aryvar 检索项目时,它返回 Nothing

最佳答案

另一种方法:

'1 form with:
'  1 command button: name=Command1

Option Explicit

Private Sub Command1_Click()
  Dim intIndex As Integer
  'dim an array with undefined boundaries
  Dim intArray() As Integer
  'set boundaries
  ReDim intArray(10) As Integer
  'fill array with values
  For intIndex = 0 To 10
    intArray(intIndex) = intIndex * intIndex
  Next intIndex
  'show the data from the initial array
  ShowArray intArray
  'remove the 6th item (index=5)
  intArray = RemoveItem(5, intArray)
  'show the data of the resulting array (with the 6h item removed)
  ShowArray intArray
End Sub

Private Function RemoveItem(intItem As Integer, intSrc() As Integer) As Integer()
  Dim intIndex As Integer
  Dim intDest() As Integer
  Dim intLBound As Integer, intUBound As Integer
  'find the boundaries of the source array
  intLBound = LBound(intSrc)
  intUBound = UBound(intSrc)
  'set boundaries for the resulting array
  ReDim intDest(intLBound To intUBound - 1) As Integer
  'copy items which remain
  For intIndex = intLBound To intItem - 1
    intDest(intIndex) = intSrc(intIndex)
  Next intIndex
  'skip the removed item
  'and copy the remaining items, with destination index-1
  For intIndex = intItem + 1 To intUBound
    intDest(intIndex - 1) = intSrc(intIndex)
  Next intIndex
  'return the result
  RemoveItem = intDest
End Function

Private Sub ShowArray(intArray() As Integer)
  Dim intIndex As Integer
  'print all items to the form to show their value
  For intIndex = LBound(intArray) To UBound(intArray)
    Print "Item " & CStr(intIndex) & " : " & CStr(intArray(intIndex))
  Next intIndex
  'print an empty line to separate the arrays in displaying
  Print
End Sub

差异:

  • 返回数组而不是传递 byref
  • 使用一个临时数组,该数组被调暗到正确的大小,而不是在最后重新保存
  • 复制保留相同索引的项目,仅移动已删除项目之后的项目

关于arrays - 从数组中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30364475/

相关文章:

svn - 有没有人在 VB6 应用程序和源代码管理方面取得过任何成功?

vb6 - 在 Visual Basic 6.0 : creating dynamic control array

c++ - 类函数中数组的长度

c++ - 缺少方法: SXS and Controls.的奇怪案例在 "object doesn'中添加结果支持此属性或方法”?

c - 在 c 中跳过空格但不换行而不中断并继续

c++ - 查找指向数组最大值的指针

vb6 - 在 VB6 中,在文件夹名称包含空格的路径中执行 .bat 文件时出现问题

sql - 累积过去 12 个月的月度总数

c - 如何检查整数是否是数组中元素的线性组合?

arrays - 搜索重复元素数组