1 避免使用STL
在COM/ATL编程时,最好避免使用STL中的集合类,ATL的目的是编写COM组件,而COM组件的目的则是为了分布式共享,STL中标准集合类在设计时并没有为这个目的服务,举一个简单的例子,COM中常使用接口,接口的赋值会有特定的需求,标准容器的赋值考虑的只是基于值的赋值。
2 ATL提供了自己的集合类——CATLMap,CATLList, CATLArray, 具体可以查看MSDN, 可惜网络上(包括MSDN)给出的Sample实在太少了,下面给出CATLMap使用的几个例子,希望大家能够触类旁通
举例1:
int main(intargc, char* argv[])
{
// Create a map which stores a double
// value using an integer key
CAtlMap<int, double> mySinTable;
inti;
// Initialize the Hash Table
mySinTable.InitHashTable(257);
// Add items to the map
for (i=0; i<90; i++)
mySinTable[i]=sin(i);
// Confirm the map is valid
mySinTable.AssertValid();
// Confirm the number of elements in the map
ATLASSERT(mySinTable.GetCount()==90);
// Remove elements with even key values
for (i=0; i<90; i+=2)
mySinTable.RemoveKey(i);
// Confirm the number of elements in the map
ATLASSERT(mySinTable.GetCount()==45);
// Walk through all the elements in the map.
// First, get start position.
POSITION pos;
int key;
double value;
pos = mySinTable.GetStartPosition();
// Now iterate the map, element by element
while (pos != NULL) {
key = mySinTable.GetKeyAt(pos);
value = mySinTable.GetNextValue(pos);
}
return 0;
}
举例2:
class Person
{
Person( int id, CString name)
{
mID= id;
mName = name;
}
int mID;
CString mName;
};
void main()
{
CAtlMap< int, Person> AtlMapTest;
Person p1(1,L"xiaoming");
AtlMapTest.SetAt( 1, p1);
Persont p2(2,L"zhangsan");
AtlMapTest.SetAt( 2, p2);
CAtlMap< int, Persont >::CPair* pair = NULL;
POSITION pos = AtlMapTest.GetStartPosition();
while (pos != NULL)
{
pair = AtlMapTest.GetNext(pos);
cout << "Key(" << pair->m_key<< ") Value(" << pair->m_value.mID<<" "<< pair->m_value.mName")" << endl;
}
}
本文通过两个实例介绍如何使用ATL提供的集合类CATLMap。第一个示例展示了如何创建、初始化、填充并遍历一个包含整数键和双精度浮点数值的映射。第二个示例则说明了如何在映射中存储自定义类型。
1617

被折叠的 条评论
为什么被折叠?



