假设我有一个 boolean 数组:{false, true, false, false, true, true, ...}
获取(例如)假元素的索引的最快方法(最优化)是什么?在这种情况下 0 2 3

最佳答案

for循环可能是最快的方法:

List<int> indices = new List<int>();
for (int i=0;i < theArray.Length; ++i)
{
   if (theArray[i])
   {
       indices.Add(i);
   }
}

请注意,通过预分配List<int>,您可能会花一点点速度,但会花费额外的内存:
List<int> indices = new List<int>(theArray.Length);

这样可以避免额外的内存分配。

关于c# - 获取 boolean 数组中所有假元素索引的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16970759/

10-11 19:59
查看更多