如何:从 .NET 集合转换为 STL/CLR 容器
本主题演示如何将 .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 个元素。 然后,我们使用将 IEnumerable<T> 作为参数的构造函数创建 vector
。
// 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);
}
}
The contents of the cliext::vector are:
2
3
5
7
11
在此示例中,我们将创建一个泛型 Dictionary<TKey,TValue> 并向其添加 5 个元素。 然后,我们创建一个 collection_adapter
以将 Dictionary<TKey,TValue> 包装为简单的 STL/CLR 容器。 最后,我们创建一个 map
并通过循环访问 collection_adapter
将 Dictionary<TKey,TValue> 的内容复制到 map
。 在此过程中,我们使用 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);
}
}
The contents of the cliext::map 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