示例:我有一个myClass类,它由3个私有属性组成:
然后我创建了一个myClass
list<myClass> 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
需要一个值。
我如何克服这个问题?
答案 0 :(得分:3)
如果您确定列表中的目标元素是第三个元素,那么代替此代码
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
中等于给定值的所有元素。
答案 1 :(得分:1)
使用std::list::erase()
method。