简体   繁体   English

在初始化方面比较C#中的List和C ++中的vector

[英]Comparison of List in C# and vector in C++ in terms of initialization

In C++, one can initialize a vector as 在C ++中,可以将向量初始化为

vector<int> nums1 (100, 4); // 100 integers with value 4

In additions, there is something like 此外,还有类似

vector<int> nums2 (nums1.begin() + 5, nums1.end() - 20);

Is there something similar in C# for List? C#for List中是否有类似的东西?

First one goes this: 第一个是这样的:

var result = Enumerable.Repeat(4, 100);

Second one (I´m not familiar with C++) would be this ( I suppose it means something like take elements from the fith until the 20th from the end): 第二个(我不熟悉C ++)将是这个(我想这意味着像从fith到末尾的第20个元素):

var result2 = result.Skip(5).Take(75);

Be aware that both result and result2 are just iterators and thus are lazily evaluated. 请注意, resultresult2都只是迭代器,因此被懒惰地求值。 Calling ToList or ToArray will actually materialize the collection by executing the query. 调用ToListToArray实际上将通过执行查询来实现集合。

You can do this like this by List . 您可以通过List这样做。

using System.Collections.Generic;
List<int> nums1 = new List<int>(Enumerable.Repeat(4,100)); //100 elements each with value 4
List<int> nums2 = new List<int>(nums1.Skip(5).Take(75)); // skip first 5 and take 75 elements

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM