共用方式為


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

本主題說明如何將轉換成對等的 STL/CLR 容器。NET 的集合。舉例來說,我們會示範如何將轉換 STL/CLR 向量來。NET ICollection<T> ,以及如何轉換 STL/CLR 對應來。NET IDictionary<TKey, TValue>,但此程序是所有的集合和容器相類似。

從容器中建立集合

  • 使用下列任一方法:

    • 若要將轉換為容器的一部份,呼叫 make_collection 變數,並賦予 begin iterator 及 STL/CLR 容器的結尾 iterator,複製到。NET 的集合。這個樣板函式會接受 STL/CLR iterator 作為樣板引數。第一個範例會示範這個方法。

    • 若要轉換整個容器,轉型為適當的容器。NET 的集合物件介面或介面的集合。第二個範例會示範這個方法。

範例

在這個範例中,我們會建立 STL/CLR vector將 5 的項目加入其中。接下來,我們建立。NET 的集合,藉由呼叫make_collection函式。最後,我們會顯示新建立的集合的內容。

// 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);
    }
}
  

在這個範例中,我們會建立 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);
    }
}
  

請參閱

工作

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

參考

range_adapter (STL/CLR)

其他資源

STL/CLR 程式庫參考