方法: STL/CLR コンテナーを .NET コレクションに変換する

このトピックでは、STL/CLR コンテナーを同等の .NET コレクションに変換する方法について説明します。 例として、STL/CLR の vector を .NET の ICollection<T> に変換する方法と、STL/CLR の map を .NET の IDictionary<TKey,TValue> に変換する方法を示しますが、その手順はすべてのコレクションやコンテナーで類似しています。

コンテナーからコレクションを作成するには

  1. 以下のいずれかの方法を使用します。

    • コンテナーの一部を変換するには、make_collection 関数を呼び出し、.NET コレクションにコピーする STL/CLR コンテナーの開始反復子と終了反復子を渡します。 この関数テンプレートは、STL/CLR 反復子をテンプレート引数として受け取ります。 1 つ目の例では、この方法を示します。

    • コンテナー全体を変換するには、コンテナーを適切な .NET コレクション インターフェイスまたはインターフェイス コレクションにキャストします。 2 つ目の例では、この方法を示します。

この例では、STL/CLR vector を作成し、それに 5 つの要素を追加します。 次に、make_collection 関数を呼び出して、.NET コレクションを作成します。 最後に、新しく作成されたコレクションの内容を表示します。

// cliext_convert_vector_to_icollection.cpp
// compile with: /clr

#include <cliext/adapter>
#include <cliext/vector>

using namespace cliext;
using namespace System;
using namespace System::Collections::Generic;

int main(array<System::String ^> ^args)
{
    cliext::vector<int> primeNumbersCont;
    primeNumbersCont.push_back(2);
    primeNumbersCont.push_back(3);
    primeNumbersCont.push_back(5);
    primeNumbersCont.push_back(7);
    primeNumbersCont.push_back(11);

    System::Collections::Generic::ICollection<int> ^iColl =
        make_collection<cliext::vector<int>::iterator>(
            primeNumbersCont.begin() + 1,
            primeNumbersCont.end() - 1);

    Console::WriteLine("The contents of the System::Collections::Generic::ICollection are:");
    for each (int i in iColl)
    {
        Console::WriteLine(i);
    }
}
The contents of the System::Collections::Generic::ICollection are:
3
5
7

この例では、STL/CLR map を作成し、それに 5 つの要素を追加します。 次に、.NET の IDictionary<TKey,TValue> を作成し、それに map を直接割り当てます。 最後に、新しく作成されたコレクションの内容を表示します。

// cliext_convert_map_to_idictionary.cpp
// compile with: /clr

#include <cliext/adapter>
#include <cliext/map>

using namespace cliext;
using namespace System;
using namespace System::Collections::Generic;

int main(array<System::String ^> ^args)
{
    cliext::map<float, int> ^aMap = gcnew cliext::map<float, int>;
    aMap->insert(cliext::make_pair<float, int>(42.0, 42));
    aMap->insert(cliext::make_pair<float, int>(13.0, 13));
    aMap->insert(cliext::make_pair<float, int>(74.0, 74));
    aMap->insert(cliext::make_pair<float, int>(22.0, 22));
    aMap->insert(cliext::make_pair<float, int>(0.0, 0));

    System::Collections::Generic::IDictionary<float, int> ^iDict = aMap;

    Console::WriteLine("The contents of the IDictionary are:");
    for each (KeyValuePair<float, int> ^kvp in iDict)
    {
        Console::WriteLine("Key: {0:F} Value: {1}", kvp->Key, kvp->Value);
    }
}
The contents of the IDictionary are:
Key: 0.00 Value: 0
Key: 13.00 Value: 13
Key: 22.00 Value: 22
Key: 42.00 Value: 42
Key: 74.00 Value: 74

関連項目

STL/CLR ライブラリ リファレンス
方法: .NET コレクションを STL/CLR コンテナーに変換する
range_adapter (STL/CLR)