How to: 轉換的來源。NET 集合至 STL/CLR 容器

本主題說明如何將轉換。NET 為其對等的 STL/CLR 容器的集合。我們可以做為範例顯示如何轉換。NET List<T> STL/clr 向量 ,以及如何轉換。NET Dictionary<TKey, TValue> STL/clr 對應,但此程序是所有的集合和容器相類似。

若要從集合中建立容器

  • 若要將整個集合,建立 STL/CLR 容器,並將集合傳遞至建構函式。

    第一個範例會示範這項程序。

-或-

  1. 建立一個泛用 STL/CLR 容器藉由建立 collection_adapter 物件。這個範本的類別會取得。NET 的集合物件做為引數的介面。若要確認是否支援哪一個介面,請參閱collection_adapter (STL/CLR)

  2. 將複製的內容。NET 至容器的集合。這可透過使用 STL/CLR 演算法,或重複。NET 的集合,並插入 STL/CLR 容器中的每個項目的複本。

    第二個範例會示範這項程序。

範例

在這個範例中,我們可以建立泛型List<T>將 5 的項目加入其中。接下來,建立vector使用的建構函式IEnumerable<T>做為引數。

// cliext_convert_list_to_vector.cpp
// compile with: /clr

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

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

int main(array<System::String ^> ^args)
{
    List<int> ^primeNumbersColl = gcnew List<int>();
    primeNumbersColl->Add(2);
    primeNumbersColl->Add(3);
    primeNumbersColl->Add(5);
    primeNumbersColl->Add(7);
    primeNumbersColl->Add(11);

    cliext::vector<int> ^primeNumbersCont =
        gcnew cliext::vector<int>(primeNumbersColl);

    Console::WriteLine("The contents of the cliext::vector are:");
    cliext::vector<int>::const_iterator it;
    for (it = primeNumbersCont->begin(); it != primeNumbersCont->end(); it++)
    {
        Console::WriteLine(*it);
    }
}
  

在這個範例中,我們可以建立泛型Dictionary<TKey, TValue>將 5 的項目加入其中。接下來,建立collection_adapter來包裝Dictionary<TKey, TValue>做為簡單的 STL/CLR 容器。最後,我們會建立map ,並將複製的內容Dictionary<TKey, TValue>map重複collection_adapter。在這個過程中,建立新的組藉由使用make_pair變數,並插入新的組,直接在map

// cliext_convert_dictionary_to_map.cpp
// compile with: /clr

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

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

int main(array<System::String ^> ^args)
{
    System::Collections::Generic::Dictionary<float, int> ^dict =
        gcnew System::Collections::Generic::Dictionary<float, int>();
    dict->Add(42.0, 42);
    dict->Add(13.0, 13);
    dict->Add(74.0, 74);
    dict->Add(22.0, 22);
    dict->Add(0.0, 0);

    cliext::collection_adapter<System::Collections::Generic::IDictionary<float, int>> dictAdapter(dict);
    cliext::map<float, int> aMap;
    for each (KeyValuePair<float, int> ^kvp in dictAdapter)
    {
        cliext::pair<float, int> aPair = cliext::make_pair(kvp->Key, kvp->Value);
        aMap.insert(aPair);
    }

    Console::WriteLine("The contents of the cliext::map are:");
    cliext::map<float, int>::const_iterator it;
    for (it = aMap.begin(); it != aMap.end(); it++)
    {
        Console::WriteLine("Key: {0:F} Value: {1}", it->first, it->second);
    }
}
  

請參閱

工作

How to: 從 STL/CLR 容器,以進行轉換。NET 的集合

參考

adapter (STL/CLR)

其他資源

STL/CLR 程式庫參考