简体   繁体   English

如何根据位置删除列表中的特定项目

[英]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类:

  1. string itemName 字符串itemName
  2. float amount 浮动金额
  3. string date 字符串日期

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] [金额] [日期]

  1. myproductA 10 011214 myproductA 10 011214

  2. myproductB 20 010115 myproductB 20 010115

  3. myproductC 30 020115 myproductC 30 020115

  4. 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.

相关问题 如何通过将第一个插入保留在其 position 中来对插入列表中的元素的 rest 进行排序? - 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 change any item's position dynamically based on user input? 如何根据设备节点名称以编程方式删除闪存驱动器? - How do I programatically remove a flash drive based on its device node name? 使用指针从列表中删除项目 - Remove item from a list using its pointer 如何删除QPlainTextEdit及其内容之间的空间 - How do I remove the space between QPlainTextEdit and its contents 如何写入 wstring 数组中的特定位置? - How do I write to a specific position in a wstring array? 如何将一对插入向量的特定 position 中? - How do I insert a pair into a specific position of vector? 如何从具有特定值的 stl 向量中删除项目? - How do I remove an item from a stl vector with a certain value? 如何根据其内容确定QGraphicsTextItem的boundingRect()? - How do I determine the boundingRect() of a QGraphicsTextItem based on its contents? 如何更改CListBox / CComboBox中特定项的字体 - How do I change the font of a specific item in a CListBox/CComboBox
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM