std :: vector <t> ::在swift中调整等效值

时间:2016-12-17 13:45:52

标签: c++ swift

  

std::vector<T>::resize

     

调整容器大小,使其包含n个元素。

以下代码不会导致out of range崩溃:

std::vector<int> vec; //0 items contained
vec.resize(10); // 10 items contained, using default constructor/initial value
cout << vec[5]; // prints 0

我在swift Array中找不到这个方法的等价物

var arr = [Int]()
arr.reserveCapacity(10)
print(arr[0]) // crashes because there is nothing contained in this array, although its capacity is set to 10

Array(repeating: T, count: Int)不满足我的请求,因为我需要动态地resize一个数组,即正在调整大小的数组可能在开头包含一些数据。

std::vector<int> vec; 
// something happend here and vec is now [1, 2, 3] 
// and I need a 6-element vector for subsequent processing. crop if vec is larger than 6 or fulfill with 0 if vec is smaller than 6
vec.resize(6) // this method exactly do what I wants
// For swift, I can't re-initiate an Array with the repeating constructor because it will overwrite the existing data

是否有内置的swift Array方法来实现这一目标?或者我只能为它写一个扩展名?

1 个答案:

答案 0 :(得分:0)

我抓了一个扩展(未经测试)

extension Array {
    mutating func resize(_ size: Int, placeholder: Element) {
        var n = size
        if count < n {
            if capacity < n + count {
                reserveCapacity(n + count)
            }
            repeat {
                append(placeholder)
                n = n - 1
            } while n > 0
        } else if count > n {
            removeLast(count - n)
        }
    }
}