如何:从 STL/CLR 容器转换为 .NET 集合
本主题演示如何将 STL/CLR 容器转换为其等效的 .NET 集合。 例如,我们将演示如何将 STL/CLR 向量转换为 .NET ICollection<T>,以及如何将 STL/CLR 映射转换为 .NET IDictionary<TKey,TValue>,但该过程适用于所有集合和容器。
从容器创建集合
使用下列方法之一:
若要转换容器的一部分,请调用 make_collection 函数,并传递要复制到 .NET 集合中的 STL/CLR 容器的开始迭代器和结束迭代器。 此函数模版将 STL/CLR 迭代器作为模板参数。 第一个示例演示了此方法。
若要转换整个容器,请将容器强制转换为适当的 .NET 集合接口或接口集合。 第二个示例演示了此方法。
示例
在此示例中,我们创建一个 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)