[英]How do I remove a specific item in a list based on its position
Example: I have a class of myClass which consists of 3 private attributes: 示例:我有一个包含3个私有属性的myClass类:
Then I create a list of myClass
然后我创建一个
myClass
列表
list<myClass> mytemp;
In my mytemp
I store a few items inside: 在我的
mytemp
我在mytemp
存储了一些物品:
[ itemName ] [ amount ] [ date ]
[itemName] [金额] [日期]
myproductA 10 011214
myproductA 10 011214
myproductB 20 010115
myproductB 20 010115
myproductC 30 020115
myproductC 30 020115
myproductD 40 040115
myproductD 40 040115
I would like to delete myproductC 我想删除myproductC
I currently have: 我目前有:
list<myClass>::iterator p=mytemp.begin();
//productC would be list(3)
p++; p++; p++;
//therefore remove:
mytemp.remove(p);
Am I right to say that? 我说对吗? However
p
is an iterator, but list::remove
wants a value. 但是
p
是一个迭代器,但是list::remove
一个值。
How do I overcome this problem? 我该如何克服这个问题?
If you are sure that the target element in the list is the third element then instead of this code 如果您确定列表中的目标元素是第三个元素,则代替此代码
list<myClass>::iterator p=mytemp.begin();
//productC would be list(3)
p++; p++; p++;
//therefore remove:
mytemp.remove(p);
You can replace it with this, if you are using C++11 or later: 如果您使用的是C ++ 11或更高版本,则可以用此替换:
mytemp.erase( std::next( mytemp.begin(), 2 ) );
Or this if you are using an older version: 如果您使用的是旧版本,请执行以下操作:
list<myClass>::iterator p = mytemp.begin();
std::advance( p, 2 );
mytemp.erase( p );
To use std::next()
or std::advance()
, you need #include <iterator>
. 要使用
std::next()
或std::advance()
,您需要#include <iterator>
。
As for the method remove()
, it removes all elements of the list
that are equal to a given value. 至于方法
remove()
,它将删除list
中等于给定值的所有元素。
使用std::list::erase()
方法 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.