如何通过过滤在swift中就地修改整数数组

时间:2016-06-12 19:10:30

标签: arrays swift filtering

可以在swift中过滤这样的数组:

var numbers = Array(1...1000000)
numbers = numbers.filter( { return $0 % 2 == 0  } ) 

是否可以过滤并避免在完成过滤时发生的复制操作,例如改变原始数组。

与此伪代码类似:     numbers.MutablefilterOperation({return $ 0%2 == 0})

在C ++中,与上面Swift中发生的事情相同的是:

std::vector<int> originalNumbers(1000000);
std::vector<int> newNumbers;
std::copy_if (originalNumbers.begin(), originalNumbers.end(), std::back_inserter(newNumbers), [](int i) { return i % 2 == 0 } );

出于性能原因,我希望实现的目标:

std::vector<int> originalNumbers(1000000);
auto pos = std::remove_if(originalNumbers.begin(), originalNumbers.end(), [](int x) { return x % 2 == 0; });
originalNumbers.erase(pos, originalNumbers.end());

2 个答案:

答案 0 :(得分:2)

此实现应执行过滤,而不必在过程中创建整个数组的临时副本(除非其副本被另一个变量引用,请参见“写入时复制”)

extension Array {
    mutating func filterInPlace(isIncluded: (Element) throws -> Bool) rethrows {
        var writeIndex = self.startIndex
        for readIndex in self.indices {
            let element = self[readIndex]
            let include = try isIncluded(element)
            if include {
                if writeIndex != readIndex {
                    self[writeIndex] = element
                }
                writeIndex = self.index(after: writeIndex)
            }
        }
        self.removeLast(self.distance(from: writeIndex, to: self.endIndex))
    }
}

// example:
var arr = [6,2,6,5,2,5,6,2,2,1,6,7,3]
arr.filterInPlace { $0 % 2 == 1 }
print(arr) // [5, 5, 1, 7, 3]

答案 1 :(得分:1)

任何mLayoutManager = new MyCustomLayoutManager(getActivity()); mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.smoothScrollToPosition(position); 都是Array,是值类型。它不能被改变,只能被复制或替换。

Structures and Enumerations Are Value Types

如果你想要一个引用类型,你必须使用struct来实现你自己的可变类型的数组 - 或者使用Foundation&#39; class

如果您想简化代码,以便将其称为变异函数,则可以使用NSMutableArray来执行此操作:

extension