本主题演示如何将 .NET 集合为其等效 STL/CLR 容器。我们例如演示如何将 .NET List<T> 为 STL/CLR 向量 以及如何转换 .NET Dictionary<TKey, TValue> 为 STL/CLR 映射,但是,该过程为所有集合和容器是类似的。
创建从集合的容器
若要将整个集合,请创建一个 STL/CLR 容器并将该集合传递给构造函数。
第一个示例将演示此过程。
- 或 -
通过创建 collection_adapter 对象创建泛型 STL/CLR 容器。此模板类采用 .NET 集合接口作为参数。若要验证哪些接口支持,请参见 collection_adapter (STL/CLR)。
复制 .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);
}
}