【问题标题】:search for index in array by value with multiple reapeated values按具有多个重复值的值在数组中搜索索引
【发布时间】:2019-07-10 12:25:30
【问题描述】:

我有一些这样的代码

dim pos, arr, val
arr = Array("a", "b", "c", "d")
val = "b"

pos = Application.Match(val, arr, False)
If Not IsError(pos) Then
MsgBox pos
End If

这很好用

除了现在我需要做一些更复杂的事情,如果我有一个像这样的数组怎么办

arr = Array("a", "b", "b", "b","c","c","d")

我想返回数组中所有出现该值的索引。

我知道你可以使用 isinarray 但这只会告诉你值是否存在,我需要知道数组中的哪些索引包含指定的值。

有没有办法在不循环整个数组的情况下做到这一点?

【问题讨论】:

  • 不是没有循环。
  • 不要害怕循环数组。这是相当有效的。 (没有高效的是在一个范围内循环)。

标签: arrays excel vba indexing


【解决方案1】:

您必须执行一个包含两个循环的函数(如for)并将要返回的位置存储在其他数组(indexes)中。它可能看起来像这样的伪代码:

function(int[] getIndexes -> { char[] array, char value }) 
    int indexes_found -> 0

    // Supposing that the array position starts at zero. 
    // This is to know the size of idexes array.
    for(int array_pos -> 0, array_pos < sizeof(array), array_pos -> array_pos + 1)

        if(value isEqualsTo array[array_pos])
            indexes_found -> indexes_found + 1
        end(if)
    end(for)

    // The array to be returned will have a size of idexes_found value.
    int[idexes_found] indexes

    // This is to get the next position in indexes array.
    // Remember, size ofindexes is less than or equals to size of array
    int index_pos -> 0

    for(int array_pos -> 0, array_pos < sizeof(array), array_pos -> array_pos + 1)
        if(value isEqualsTo array[array_pos])
            idexes[index_pos] -> array_pos
            index_pos -> index_pos + 1
        end(if)
    end(for)

    return idexes
end(function)

I/O 示例:

输入:

char[5] letters -> { 'a', 'b', 'c', 'a', 'b' }
char value -> 'b'

int[] indexes -> getIndexes(letters, value)

输出:

indexes -> { 1, 4 }

希望对你有所帮助。

您好。

【讨论】:

    猜你喜欢
    • 2019-03-11
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 2015-09-08
    • 1970-01-01
    相关资源
    最近更新 更多