英文:
Wanted: Swift Class of fixed memory as array
问题
我需要一个类,为通用类型<T>分配内存块。它应该提供所有通常的功能,如索引、添加、排序等。但与内置功能相比,每个元素都不应该有动态内存分配。因此,它是一个相对静态的数组。我不想重复造轮子,所以我想知道是否已经有类似的库或插件等。有什么提示吗?
英文:
I need a class, which allocates a memory block for generic Type <T>. It should offer all usual features like indexing, adding, sort etc. But in contrast to the build in functionality, there should be no dynamic memory allocation for each element. So it is a relatively static array. I don't want to reinvent the wheel, so I ask if there is already something as a library or an addin etc. Any hints?
答案1
得分: 1
希望这对你有所帮助。
class StaticArray<T> {
private var data: [T]
private let capacity: Int
init(capacity: Int) {
self.capacity = capacity
data = Array<T>(repeating: nil, count: capacity)
}
subscript(index: Int) -> T {
get {
return data[index]
}
set {
data[index] = newValue
}
}
func append(_ value: T) {
// 在追加之前检查数组是否已满
guard data.count < capacity else {
return
}
data.append(value)
}
func sort() {
data.sort()
}
}
英文:
Hope this helps you.
class StaticArray<T> {
private var data: [T]
private let capacity: Int
init(capacity: Int) {
self.capacity = capacity
data = Array<T>(repeating: nil, count: capacity)
}
subscript(index: Int) -> T {
get {
return data[index]
}
set {
data[index] = newValue
}
}
func append(_ value: T) {
// Check if array is full before appending
guard data.count < capacity else {
return
}
data.append(value)
}
func sort() {
data.sort()
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论