D Language
ダイナミックアレイ&スライス
サーチ…
構文
- <タイプ> [] <名前>;
備考
スライスは既存のメモリ上に新しいビューを生成します。彼らは新しいコピーを作成しません。スライスにそのメモリへの参照またはスライスされた部分が保持されていない場合は、ガベージコレクタによって解放されます。
スライスを使用すると、1つのメモリブロックで動作し、実際に作業する必要のある部分のみをスライスするパーサーなど、非常に効率的なコードを書くことができます。新しいメモリブロックを割り当てる必要はありません。
宣言と初期化
import std.stdio;
void main() {
int[] arr = [1, 2, 3, 4];
writeln(arr.length); // 4
writeln(arr[2]); // 3
// type inference still works
auto arr2 = [1, 2, 3, 4];
writeln(typeof(arr2).stringof); // int[]
}
配列演算
import std.stdio;
void main() {
int[] arr = [1, 2, 3];
// concatenate
arr ~= 4;
writeln(arr); // [1, 2, 3, 4]
// per element operations
arr[] += 10
writeln(arr); // [11, 12, 13, 14]
}
スライス
import std.stdio;
void main() {
int[] arr = [1, 2, 3, 4, 5];
auto arr2 = arr[1..$ - 1]; // .. is the slice syntax, $ represents the length of the array
writeln(arr2); // [2, 3, 4]
arr2[0] = 42;
writeln(arr[1]); // 42
}
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow