简体   繁体   English

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

[英]CPtrList - How to get index of a element?

How to get index of a element in the CPtrList ?如何获取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;

If I subtract pos2 from pos1 I am getting the value 12 .如果我从pos1中减去pos2我得到的值12 I expect the value 1 since it is 2nd element.我期望值1因为它是第二个元素。

How to get index of a element?如何获取元素的索引?

CTypedPtrList is implemented as a linked list. CTypedPtrList被实现为链表。 The POSITION pointers do not point into a contiguous array, so pointer arithmetic will not and cannot work (it's also illegal by the C++ rules). POSITION指针不指向连续数组,因此指针运算不会也无法工作(C++ 规则也是非法的)。

The only way to get the index of a POSITION is to actually iterate backwards all the way to the beginning of the list and count the steps.获得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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM