Created
April 21, 2018 16:46
-
-
Save ufcpp/b84e39371ba04ae2c07fbe0b874a6d1e to your computer and use it in GitHub Desktop.
Cではよくやる p != end イテレーターループ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.CompilerServices; | |
class Program | |
{ | |
static void Main() | |
{ | |
var array = new[] { 1, 3, 5, 2, 4 }; | |
PointerInit(array, 1); | |
Console.WriteLine(string.Join(", ", array)); | |
RefInit(array, 2); | |
Console.WriteLine(string.Join(", ", array)); | |
} | |
private unsafe static void PointerInit(int[] array, int value) | |
{ | |
fixed (int* p = array) | |
{ | |
// C 言語とかではよくやる書き方 | |
var end = p + array.Length; | |
for (var i = p; i != end; i++) | |
{ | |
*i = value; | |
} | |
} | |
} | |
private unsafe static void RefInit(int[] array, int value) | |
{ | |
if (array.Length == 0) return; | |
ref var end = ref Unsafe.Add(ref array[0], array.Length); | |
for (ref var r = ref array[0]; !Unsafe.AreSame(ref r, ref end); r = ref Unsafe.Add(ref r, 1)) | |
{ | |
r = value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment