CPtrList - 如何获取元素的索引?

use*_*mgs 1 c++ mfc

如何获取元素的索引CPtrList

class CAge
{

public:

CAge(int nAge){m_nAge=nAge;}

int m_nAge;

};



typedef CTypedPtrList <CPtrList, CAge*> CAgePtrList;

CAgePtrList list;

POSITION pos;

CAge *p1 = new CAge(21);

CAge *p2 = new CAge(40);

list.AddTail(p1);
list.AddTail(p2); 

POSITION pos1 = list.GetHeadPosition();
POSITION pos2 = list.Find(p2,NULL);
int nIndex=pos2-pos1;
Run Code Online (Sandbox Code Playgroud)

如果我减去pos2pos1我得到的价值12。我期望该值,1因为它是第二个元素。

如何获取元素的索引?

dxi*_*xiv 5

CTypedPtrList被实现为一个链表。该POSITION指针不点变成一个连续的数组,所以指针运算不会也不能工作(这也是由C ++规则是非法的)。

获取 a 的索引的唯一方法POSITION是实际上一直向后迭代到列表的开头并计算步数。

int nIndex = -1;

for(POSITION pos = pos2; pos; list.GetPrev(pos))
    nIndex++;

// nIndex is the 0-based index of POSITION 'pos2' in 'list'
//           or -1 if pos2 == NULL
Run Code Online (Sandbox Code Playgroud)