2016-12-17 6 views
2

std::vector<T>::resizeのstd ::ベクトル<T> ::迅速

に等価なサイズ変更は、コンテナのサイズを変更します。

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)がない私は、迅速な配列では、この方法と同等のものを見つけていない

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

次のコードは、out of rangeクラッシュが発生することはありませんアレイを動的に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 

迅速なアレイは、これを達成するための組み込みの方法はありますか?または私はそれのための拡張子を書くことができますか?

+0

を傷... – Phil1970

答えて

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) 
     } 
    } 
}