简体   繁体   中英

CPtrList - How to get index of a element?

How to get index of a element in the 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 . I expect the value 1 since it is 2nd element.

How to get index of a element?

CTypedPtrList is implemented as a linked list. 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).

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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