gpt4 book ai didi

c++ - std::vector::resize 等价于 swift

转载 作者:搜寻专家 更新时间:2023-11-01 05:35:38 26 4
gpt4 key购买 nike

<分区>

std::vector<T>::resize

Resizes the container so that it contains n elements.

以下代码不会导致 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 是否有内置方法来实现这一点?或者我只能为它写一个扩展?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com