![](/img/trans.png)
[英]How do I sort rest of the elements that I insert in a list by keeping the first insertion remain in its position?
[英]How do I remove a specific item in a list based on its position
示例:我有一個包含3個私有屬性的myClass類:
然后我創建一個myClass
列表
list<myClass> mytemp;
在我的mytemp
我在mytemp
存儲了一些物品:
[itemName] [金額] [日期]
myproductA 10 011214
myproductB 20 010115
myproductC 30 020115
myproductD 40 040115
我想刪除myproductC
我目前有:
list<myClass>::iterator p=mytemp.begin();
//productC would be list(3)
p++; p++; p++;
//therefore remove:
mytemp.remove(p);
我說對嗎? 但是p
是一個迭代器,但是list::remove
一個值。
我該如何克服這個問題?
如果您確定列表中的目標元素是第三個元素,則代替此代碼
list<myClass>::iterator p=mytemp.begin();
//productC would be list(3)
p++; p++; p++;
//therefore remove:
mytemp.remove(p);
如果您使用的是C ++ 11或更高版本,則可以用此替換:
mytemp.erase( std::next( mytemp.begin(), 2 ) );
如果您使用的是舊版本,請執行以下操作:
list<myClass>::iterator p = mytemp.begin();
std::advance( p, 2 );
mytemp.erase( p );
要使用std::next()
或std::advance()
,您需要#include <iterator>
。
至於方法remove()
,它將刪除list
中等於給定值的所有元素。
使用std::list::erase()
方法 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.