快速搜索数组的倒序

4

我有一个数组想要进行反向搜索,我想得到原始数组的结果索引,而不是实际值。如何将ReverseRandomAccessIndex转换为“正常”的索引?

let arr = [1,2,3,4,5]
if let index = arr.reverse().indexOf(2) //index is ReverseRandomAccessIndex
{
 let searchvalue = arr.reverse()[index]
}

NormalIndex = (Count - 1) - ReverseIndex,这样行吗? - holex
你不能直接获取索引。它是一个ReverseRandomAccessIndex。请参见下面的答案。 - user965972
1个回答

2
很简单:
let arr = [1, 2, 3, 4, 5]

if let index = arr.reverse().indexOf(2)
{
    let searchvalue = arr[index.base - 1]
}

base是标准库中定义的:

    /// The successor position in the underlying (un-reversed)
    /// collection.
    ///
    /// If `self` is `advance(c.reverse.startIndex, n)`, then:
    /// - `self.base` is `advance(c.endIndex, -n)`.
    /// - if `n` != `c.count`, then `c.reverse[self]` is 
    ///   equivalent to `[self.base.predecessor()]`.
    public let base: Base

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接