在数组中搜索下一个实例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在数组中搜索下一个实例相关的知识,希望对你有一定的参考价值。

For i = 1 To max
    matchFoundIndex = Application.Match(arr(i), arr, 0)
Next

上面的代码返回arr(i)中第一次出现的arr。但是,在arr(i)中可能存在arr的其他情况。简而言之,我怎样才能在arr(i)中有效地找到arr的下一个实例(避免经典的n ^ 2循环)?

答案

你可以“隐藏”找到的所有匹配并继续使用Application.Match()

Function GetIndexes(arr As Variant) As String
    Dim tempArr As Variant, matchIndex As Variant, element As Variant
    Dim matchIndexes As String

    tempArr = arr ' use a temporary array not to spoil the passed one
    For Each element In tempArr
        If element <> "|||" Then 'skip elements already marked as "already found"
            matchIndexes = ""
            matchIndex = Application.Match(element, tempArr, 0) 'search for array element matching current one
            Do
                matchIndexes = matchIndexes & matchIndex & " "
                tempArr(matchIndex - 1) = "|||" 'mark found array element as "already found"
                matchIndex = Application.Match(element, tempArr, 0) 'search for next array element matching current one
            Loop While Not IsError(matchIndex) ' loop until no occurrences of current array element
            GetIndexes = GetIndexes & "element '" & element & "' found at indexes: " & Replace(Trim(matchIndexes), " ", ",") & vbCrLf
        End If
    Next
End Function

你可以利用如下:

Sub main()
    Dim i As Long
    Dim arr As Variant

    arr = Array("a1", "a2", "a3", "a1", "a2", "a3")

    MsgBox GetIndexes(arr)

End Sub

以上是关于在数组中搜索下一个实例的主要内容,如果未能解决你的问题,请参考以下文章

如何创建片段以重复变量编号中的代码行

创建片段而不从 java 代码实例化它

如何在没有 dralogfragment 实例的情况下从适配器显示对话框片段?

字符串数组中字符串(多个实例)的递归二进制搜索 - C#

仅在父片段中的操作栏中显示搜索视图

片段事务中的实例化错误