开发者

What is C# Equivalent to C++ STL fill method

开发者 https://www.devze.com 2023-03-25 21:52 出处:网络
In C++, we can set a range of values of an array(and other similar containers) using fill. For example,

In C++, we can set a range of values of an array(and other similar containers) using 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.

What is the closest C# equivalent to this.


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.

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.


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. 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:

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;
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消