簡體   English   中英

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

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

如何獲取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;

如果我從pos1中減去pos2我得到的值12 我期望值1因為它是第二個元素。

如何獲取元素的索引?

CTypedPtrList被實現為鏈表。 POSITION指針不指向連續數組,因此指針運算不會也無法工作(C++ 規則也是非法的)。

獲得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