![](/img/trans.png)
[英]How can a CPtrList->RemoveHead() cause an CInvalidArgumentException?
[英]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.