简体   繁体   English

什么是C#等效于C ++ STL填充方法

[英]What is C# Equivalent to C++ STL fill method

In C++, we can set a range of values of an array(and other similar containers) using fill. 在C ++中,我们可以使用fill设置数组(和其他类似容器)的值范围。

For example, 例如,

fill(number, number+n,10);

The above code will set the first n values of the array number with the value 10. 上面的代码将数组编号的前n个值设置为值10。

What is the closest C# equivalent to this. 与此最接近的C#是什么。

There's no equivalent method but there are many ways to write similar code 没有等效的方法,但是有很多方法可以编写类似的代码

Methods from the Linq-to-Objects classes can create sequences that you can use to initialize lists but this is very different from how things in C++ actually occur. Linq-to-Objects类中的方法可以创建可用于初始化列表的序列,但这与C ++中的实际情况非常不同。

new List<char>(Enumerable.Repeat('A', 10));
new List<int>(Enumerable.Range(1, 10));

C++ can accomplish these things more generally thanks to how C++ templates work, and while simple type constraints in C# help, they do not offer the same flexibility. 由于C ++模板的工作原理,C ++可以更一般地完成这些任务,尽管C#帮助了简单的类型约束,但它们并没有提供相同的灵活性。

I'm not sure one exists, but you can code your own easily: 我不确定是否存在,但是您可以轻松编写自己的代码:

void Fill<T>(T[] array, int start, int count, T value)
{
  for (int i = start, j = 0; j < count; i++, j++)
    array[i] = value;
}

Obviously missing parameter checking, but you get the drill. 显然缺少参数检查,但是您可以进行练习。

There is no direct equivalent, but you can do it in two steps. 没有直接等效项,但是您可以分两步完成。 First use Enumerable.Repeat to create an array with the same value in each element. 首先使用Enumerable.Repeat创建一个在每个元素中具有相同值的数组。 Then copy that over the destination array: 然后将其复制到目标数组:

var t = Enumerable.Repeat(value, count).ToArray();
Array.Copy(t, 0, dest, destStartIndex, count);

For other destination containers there is a lack of an equivalent to Array.Copy , but it is easy to add these as destinations, eg: 对于其他目标容器,缺少Array.Copy的等效Array.Copy ,但是将它们添加为目标很容易,例如:

static void Overwrite<T>(this List<T> dest, IEnumerable<T> source, int destOffset) {
  int pos = destOffset;
  foreach (var val in source) {
    // Could treat this as an error, or have explicit count
    if (pos = dest.Length) { return; }

    dest[pos++] = val;
  }
}

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

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