Thread: Remove element from STL list

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715

    Remove element from STL list

    Hello,
    please, I need to have a list of objects that are frequently inserted and removed.
    That's why I decided to use STL list.
    However, I have problems removing elements from the list.
    For example this code won't compile:
    Code:
    #include <iostream>
    #include <list>
    #include <string>
    
    using namespace std;
    
    struct Klijent
    {
    	string ime;
    };
    
    
    int main()
    {
    	Klijent k;
    	k.ime="Name";
    
    	list<Klijent>lista;
    
    	lista.push_back(k);
    
    	lista.remove(k);
    }
    One way to slove this is to use iterators:
    Code:
    for (it = lista.begin(); it != lista.end(); ++it)
    {
    	if (it->ime == "Name")
    	{
    		lista.erase(it);
    	}
    }
    but, this gives me an exception. I don't know what is wrong.
    I wonder if there is a clever way to do this?
    There's been a while since I used STL and I almost forget it.
    Thanks in advance.
    Last edited by Micko; 07-05-2007 at 07:35 AM.
    Gotta love the "please fix this for me, but I'm not going to tell you which functions we're allowed to use" posts.
    It's like teaching people to walk by first breaking their legs - muppet teachers! - Salem

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  2. Reverse function for linked list
    By Brigs76 in forum C++ Programming
    Replies: 1
    Last Post: 10-25-2006, 10:01 AM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. link list
    By Unregistered in forum C++ Programming
    Replies: 4
    Last Post: 12-13-2001, 05:41 AM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM