userrmgs
userrmgs

Reputation: 323

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?

Upvotes: 1

Views: 606

Answers (1)

dxiv
dxiv

Reputation: 17668

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

Upvotes: 5

Related Questions