后缀数组索引越界

suffix array Index out of bounds

我有一个数组,当我为数组添加后缀并想要 select 元素时,我得到错误:索引越界。 但是当我为数组和 select 元素添加前缀时,就成功了。

后缀数组后select我应该怎么做?

代码如下:

let array = [1,2,3,4,5,6,7,8,9,10]
let suffixArray = array.suffix(5)//[6,7,8,9,10]
let prefixArray = array.prefix(5)//[1,2,3,4,5]
print(suffixArray[2])//Index out of bounds
print(prefixArray[2])//sucess print "3"

你遇到的问题是 .suffix 数组不是从 0 开始的。所以如果你想打印后缀数组中的第三个数字,你必须调用 print(suffixArray[7] .

如果您阅读 return 值 here 的说明。上面写着:

A subsequence terminating at the end of the collection with at most maxLength elements.

如果您阅读 subsequence 的说明:

A collection representing a contiguous subrange of this collection’s elements. The subsequence shares indices with the original collection.

游乐场的完整示例:

let array = [1,2,3,4,5,6,7,8,9,10]
let suffixArray = array.suffix(5) // [6,7,8,9,10]
let prefixArray = array.prefix(5) // [1,2,3,4,5]
var newSuffixArray: [Int] = []
for i in suffixArray {
    newSuffixArray.append(i)
}

print(suffixArray[7]) // 8
print(newSuffixArray[2]) // 8
print(prefixArray[2]) // 3

prefixsuffix return 一个 ArraySlice 而不是另一个 Array

以下是 ArraySlice documentation 的摘录:

Unlike Array and ContiguousArray, the starting index for an ArraySlice instance isn’t always zero. Slices maintain the same indices of the larger array for the same elements, so the starting index of a slice depends on how it was created, letting you perform index-based operations on either a full array or a slice. Sharing indices between collections and their subsequences is an important part of the design of Swift’s collection algorithms.

您可以查看 prefixArraysuffixArrayindices 属性。

通常鼓励您使用集合提供的访问元素的方法,而不是假设索引值。