确定数组是否包含全零

时间:2018-05-01 11:03:30

标签: c# .net c++-cli

我创建了以下数组:

array<UInt16>^ temp = gcnew array<UInt16>(1000);

如何判断整个数组是否已填零。

我想我可以使用TrueForAll(T),但我不确定。

4 个答案:

答案 0 :(得分:4)

var allElementsAreZero = temp.All(o => o == 0);

这很简单。

当它找到一个不满足条件的东西时它会返回,所以可能不一定会遍历整个集合:

&#34;只要能够确定结果,就会停止源的枚举。&#34;

https://msdn.microsoft.com/en-us/library/bb548541(v=vs.110).aspx

答案 1 :(得分:1)

这应该正常工作(这里我使用LINQ):

IEnumerable

P.S。数组类继承foreach

以下是var isAllZero = true; foreach (var value in values) { if (value != 0) { isAllZero = false; break; } } 的解决方案:

TrueForAll

更新

LINQ和我的LINQ代码之间的真正区别是:TrueForAll代码使用流畅(或者也可能是查询)语法,其中public class SpawnOnMap : MonoBehaviour { [SerializeField] AbstractMap _map; [SerializeField] [Geocode] string[] _locationStrings; Vector2d[] _locations; [SerializeField] float _spawnScale = 100f; [SerializeField] GameObject _markerPrefab; List<GameObject> _spawnedObjects; void Start() { _locations = new Vector2d[_locationStrings.Length]; _spawnedObjects = new List<GameObject>(); for (int i = 0; i < _locationStrings.Length; i++) { var locationString = _locationStrings[i]; _locations[i] = Conversions.StringToLatLon(locationString); var instance = Instantiate(_markerPrefab); instance.transform.localPosition = _map.GeoToWorldPosition(_locations[i], true); instance.transform.localScale = new Vector3(_spawnScale, _spawnScale, _spawnScale); _spawnedObjects.Add(instance); } } private void Update() { int count = _spawnedObjects.Count; for (int i = 0; i < count; i++) { var spawnedObject = _spawnedObjects[i]; var location = _locations[i]; spawnedObject.transform.localPosition = _map.GeoToWorldPosition(location, true); spawnedObject.transform.localScale = new Vector3(_spawnScale, _spawnScale, _spawnScale); } } } 只是正常将数组作为参数发送的函数。

答案 2 :(得分:0)

从0初始化一个计数器,然后使用for循环遍历数组并在计数器找到0时递增计数器,最后将计数器与数组大小进行比较,如果它相等,则它全部为零

答案 3 :(得分:0)

阅读C++/CLI specification,它已被填满 为0,因为您使用“new-expression”创建了它,并且元素类型的默认值为0.

  

24.2创建CLI阵列

     

CLI数组实例由包含gcnew(第15.4.6节)或...

的新表达式创建      

new-expression创建的CLI数组元素始终初始化为其默认值。