![](/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.