Can I delete a item from std::list based on pointer value?

This code is written on fly, plz ignore syntax mistakes if any.

std::list<MY_STRUCT> myList; MY_STRUCT theStruct; myList.push_back( theStruct ); myList.push_back( theStruct ); // assume I store the pointer of the last item (the 2nd item in this case). MY_STRUCT * item2 = &myList.back(); // I added another item myList.push_back( theStruct ); // now I want to delete item2 that I stored bases on its pointer. // Can myList.remove_if(...) help if so how?

I want to delete the middle item in the list by its pointer (assume I have the pointer value).

I know I can iterate through the list and look for this pointer but is there a better way? Does STL provide a function to do it..Can I use remove_if() in this case to delete the item?

-------------Problems Reply------------

Sure, list::remove_if uses whatever condition you give it. For example

template <typename T>
struct AddressIs {
T *ptr;
AddressIs(T *ptr) : ptr(ptr) {}
bool operator()(const T &object) const {
return ptr == &object;


Mankarse's point is good though - if you can use an iterator instead of a pointer to identify the item you're interested in, then you don't need to mess about with this.

Beware also that we're relying here on the fact that the address of an item in a list stays the same forever. That isn't always true of all collections, for example vector might have to relocate all the data when you call push_back. If it does, then your middle item is no longer pointed to by item2. Each collection documents which operations can invalidate iterators and/or references to elements.

Instead of keeping a pointer to the object you want to remove, why not keep an iterator?

std::list<MY_STRUCT>::iterator item2 = --mylist.end();

The remove_if algorithm doesn't actually remove anything, it just shifts stuff around. It has no knowledge of the container that the iterators point to. Of course the member function remove_if of std::list is a different thing altogether as pointed out in the comments.

Instead of getting the back item, you could get the end iterator, make sure it's not begin, decrement by one to point to the last item, and then erase that iterator directly whenever you want.

I think remove_if is a little bit of overkill for what zadane is trying to do. All that needs to be accomplished is to save the location or value of an item in order to delete that specific item later.

As Mark suggested you can store the iterator to the object and use it to delete the item with an erase call, like below:

MY_STRUCT struct;
std::list<MY_STRUCT>::iterator del_it = myList.end() - 1;

Or, if your structure has the == operator defined for MY_STRUCT, you can store the value of the object itself and use the remove method

MY_STRUCT struct1;
MY_STRUCT struct2;

Of course if you make your list a list of pointers then you don't have to worry about the == operator as it is already defined for pointer types. Just make sure that if you're iterating through the list and call erase, you need to update your iterator with the returned value.

Also, the remove method removes all elements of the passed value, so if you only want to remove 1 item at a time save the iterator and not the value.

This code is untested so I welcome any corrections.

Category:c# Views:0 Time:2011-09-08
Tags: stl

Related post

  • STL Priority Queue - deleting an item 2010-06-19

    I want to implement a timer queuing system using the C++ STL priority_queue container adapter. My problem is that I want to occasionally cancel a timer, however there are no interfaces that enable me to easily delete an item in the priority_queue tha

  • Carefully deleting N items from a "circular" vector (or perhaps just an NSMutableArray) 2011-01-13

    Imagine a std:vector (or any array conceptually) with (say) 100 things on it (0 to 99) currently. I'm treating it as a "loop". (So for example the "105"th item would actually be index 4 -- or if you "went forward 7 from index 98" the result would be

  • How to delete Work Item from Team Foundation Server 2009-03-12

    Is there a chance to delete Work Item from TFS, or all I can do is just to rename it. Update: This question was for TFS 2008. New version (2010) have out of the box solution as Rob Cannon suggested --------------Solutions------------- See this tool:

  • SharePoint: How to create/delete multiple items in a transaction 2009-07-29

    I am trying to delete multiple items in a SharePoint list with the constraint that either all of the items should be deleted or none of the items should be deleted. In short, I am looking to create more of a transactional behavior in SharePoint. I ha

  • Sharepoint Deleting an Item from a list using UpdateListItems WebService 2009-09-03

    I am trying to delete an item from a list and have the following xml <Batch PreCalc='TRUE' OnError='Continue'> <Method ID='1' Cmd='Delete'>\ <Field Name='ID'>185</Field> </Method> </Batch> This is returning the fol

  • What is the best way to delete array item in PHP? 2009-11-17

    Could you tell me your way to delete an item from array? Do you think it's good? --------------Solutions------------- That depends: $a1 = array('a' => 1, 'b' => 2, 'c' => 3); unset($a1['b']); // array('a' => 1, 'c' => 3) $a2 = array(1,

  • How could I delete an item from an array by the item's name? 2010-02-07

    Like I have an array Array('one', 'three', 'two');, and, say, I want to delete the item three, how would I do it? --------------Solutions------------- var a = ['one', 'three', 'two']; a.splice(a.indexOf('three'), 1); alert(a); for browsers that don't

  • Deleting first item of a $_COOKIE array 2010-03-26

    if I add an item to the $_COOKIE array as such: setcookie("favorites[]", "value", time()+3600); I can delete any item from the $_COOKIE[favorites] array like this: setcookie("favorites[$deletekey]", "", time()+3600); EXCEPT the first one added so thi

  • sql: delete a subtree table(id, Parentid) , delete a item with all his children 2010-05-07

    I have a table like this foo(id, parentId) -- there is a FK constraint from parentId to id and I need to delete an item with all his children and children of the children etc. anybody knows how ? --------------Solutions------------- AFAIK, SQL SERVER

  • Deleting list items via ProcessBatchData() 2010-06-14

    You can build a batch string to delete all of the items from a SharePoint list like this: 1: //create new StringBuilder 2: StringBuilder batchString= new StringBuilder(); 3: 4: //add the main text to the stringbuilder 5: batchString.Append(""); 6: 7:

  • Delete an item from ListView on OnFling event 2010-06-25

    Hi I want to delete an item from a ListView, to which have attached a GestureListener. I have overridden the method onFling for that GestureListener to return true of false based on my criteria. But I don't know how to fetch the last selected item in

  • How to delete an item from a Dictonary using LINQ in C# 2010-06-30

    I need to delete a specific item from a dictonary.. The dictonary is like dict["Key1"]="Value1" dict["Key2"]="Value2" dict["Key3"]="Value3" dict["Key4"]="Value2" How to delete the item if another item has the same value using LINQ Thanks in advance -

  • Delete an item from a list 2010-07-21

    Hey, I was trying to delete an item form a list (without using set): list1 = [] for i in range(2,101): for j in range(2,101): list1.append(i ** j) list1.sort() for k in range(1,len(list1) - 1): if (list1[k] == list1[k - 1]): list1.remove(list1[k]) pr

  • How can I delete an item from an array in VB.NET? 2010-08-10

    How can I delete an item from an array in VB.NET? --------------Solutions------------- You can't. I would suggest that you put the array elements into a List, at least then you can remove items. An array can be extended, for example using ReDim but y

  • EditorFor with a variable length list - wrong data is displayed after deleting an item 2010-08-25

    I'm trying to create a form which will be used by clients to place an order for variable amount of models. It's similar to example from Steve Sanderson's blog, but I'm not using any javascript - I just have multiple submits in my form. Everything wor

  • Deleting an item from an indexed property - JavaBeans question 2010-08-31

    I'm working with indexed properties (using struts and java/jsp). We have a dynamic table that can add/delete rows/items in the table. The adding of rows works as intended - I see the new rows in the form in the action class. The deleted rows do not g

  • how to delete an item from listview in android 2010-12-18

    My app contains a listview. Each item in listview has a delete button. But delete button could not delete an item in listview. Please tell me how can i delete an item in a listview and also in My source: public void onCreate(Bundle saved

  • Django: want to delete an item with checkbox 2011-01-28

    I have a template that displays the list of items. It has one checkbox to each item. I want to be able to remove an item from a checkbox when a checkbox is ticked. So I would need a button that deletes an item once a checkbox is selected. Here is my

  • Django: writing a view to delete an item with checkboxes 2011-02-04

    I need help writing a view that gets the POST data which then finds out which checkboxes have been checked, and then deletes the items from the database matched by id. Originally, This was a checkbox problem. In a edit order form, there are a list of

Copyright (C), All Rights Reserved.

processed in 0.211 (s). 11 q(s)