この文書の現在のバージョンと選択したバージョンの差分を表示します。
cli:array [2011/08/23 18:37] admin [array] |
cli:array [2013/12/23 09:08] |
||
---|---|---|---|
ライン 1: | ライン 1: | ||
- | {{indexmenu_n>13}} | ||
- | ====== array ====== | ||
- | arrayはcliが提供する配列です。以下の機能があります。 | ||
- | |||
- | * 配列の要素数を知ることができます。 | ||
- | * 可変長の引数をarrayで受け取れます。 | ||
- | * for eachが使えます。 | ||
- | |||
- | int型のarrayを要素数4で作る場合は以下のようにします。 | ||
- | |||
- | <code cpp> | ||
- | array<int>^ a = gcnew array<int>(4); | ||
- | array<int>^ b = gcnew array<int>(4) {1,2,3,4}; | ||
- | array<int>^ c = gcnew array<int>{1,2,3,4}; | ||
- | </code> | ||
- | |||
- | arrayは常にハンドルを用いて利用しなければなりません。またarrayの型にref classを用いることはできず、ref classのハンドルを用いなければなりません。 | ||
- | |||
- | <code cpp> | ||
- | array<Object>^ oa ; // エラー | ||
- | array<Object^>^ oa ; // OK | ||
- | </code> | ||
- | arrayの要素数を知るには、Lengthを使います。 | ||
- | |||
- | <code cpp> | ||
- | array<int>^ c = gcnew array<int>{1,2,3,4}; | ||
- | int len = c->Length; | ||
- | </code> | ||
- | |||
- | for eachを以下のようにして使えます。 | ||
- | <code> | ||
- | array<int>^ c = gcnew array<int>{1,2,3,4}; | ||
- | for each(int i in c) | ||
- | { | ||
- | System::Console::WriteLine(i); | ||
- | } | ||
- | </code> | ||
- | これは以下と同じです。 | ||
- | |||
- | <code cpp> | ||
- | array<int>^ c = gcnew array<int>{1,2,3,4}; | ||
- | for ( int i=0 ; i < c->Length; ++i ) | ||
- | { | ||
- | System::Console::WriteLine(c[i]); | ||
- | } | ||
- | </code> | ||
- | 2次元arrayは以下のように作ります。 | ||
- | |||
- | <code cpp> | ||
- | array<int,2>^ a2 = gcnew array<int,2>(4,4); | ||
- | array<int,2>^ b2 = gcnew array<int,2>{ {1,2,3,4},{1,2,3,4},{1,2,3,4},{1,2,3,4} }; | ||
- | </code> | ||
- | |||
- | System::Arrayのメソッドでarrayを色々する。 | ||
- | <code cpp> | ||
- | #include "stdafx.h" | ||
- | |||
- | using namespace System; | ||
- | |||
- | void printout(int i) | ||
- | { | ||
- | Console::WriteLine(i); | ||
- | } | ||
- | int conv(int i) | ||
- | { | ||
- | return i*2; | ||
- | } | ||
- | |||
- | bool pred(int i) | ||
- | { | ||
- | return i==4; | ||
- | } | ||
- | |||
- | int main(array<System::String ^> ^args) | ||
- | { | ||
- | array<int>^ ia = gcnew array<int>{1,2,3,4,5}; | ||
- | |||
- | Array::Reverse(ia); | ||
- | Array::Sort(ia); | ||
- | |||
- | Array::ForEach<int>(ia, gcnew Action<int>(printout)); | ||
- | |||
- | |||
- | array<int>^ ia2 = Array::ConvertAll(ia, gcnew Converter<int,int>(conv)); | ||
- | Array::ForEach<int>(ia2, gcnew Action<int>(printout)); | ||
- | |||
- | |||
- | int i4 = Array::Find(ia2, gcnew Predicate<int>(pred)); | ||
- | |||
- | |||
- | return 0; | ||
- | } | ||
- | </code> |