dynamic objects in a <list>

This is a discussion on dynamic objects in a <list> within the C++ Programming forums, part of the General Programming Boards category; Someone clear this up for me... ----------------------------------------------------------------------------------- list<Order> lst_Orders; typedef list<Order *>::iterator it; Order *ptrOrder1 = new Order; Order *ptrOrder2 ...

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    13

    dynamic objects in a <list>

    Someone clear this up for me...
    -----------------------------------------------------------------------------------

    list<Order> lst_Orders;

    typedef list<Order *>::iterator it;

    Order *ptrOrder1 = new Order;
    Order *ptrOrder2 = new Order;
    Order *ptrOrder3 = new Order;

    lst_Orders.push_back(ptrOrder1);
    lst_Orders.push_back(ptrOrder2);
    lst_Orders.push_back(ptrOrder3);

    for ( it = lst_Orders.begin(); it != lst_Orders.end(); it++ )
    {
    delete *it; // not sure
    lst_Orders.remove(it); // not sure
    }


    -----------------------------------------------------------------------------------
    Is this correct ?

  2. #2
    Registered User
    Join Date
    Dec 2001
    Posts
    421
    try to use code tags in future mate

    Code:
    typedef std::list<Order*> lst_orders; // this is a typedef, not an instance
    typedef lst_orders::iterator lst_it; // ditto
    
    lst_orders theList; // instantiate the list
    lst_it theIterator; // instantiate the iterator
    
    Order *ptrOrder1 = new Order;
    Order *ptrOrder2 = new Order;
    Order *ptrOrder3 = new Order;
    
    theList.push_back(ptrOrder1); // add to the list
    theList.push_back(ptrOrder2);
    theList.push_back(ptrOrder3);
    
    for ( theIterator = theList.begin(); theIterator != theList.end(); ++theIterator ) // make the sure the iterator is incremented first, coz theList.begin() isn't an item in the list
    {
       delete *theIterator;
       theList.remove(theIterator);
    }
    hope this helps
    U.
    Quidquid latine dictum sit, altum sonatur.
    Whatever is said in Latin sounds profound.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic objects
    By wierdbeard65 in forum C++ Programming
    Replies: 14
    Last Post: 06-26-2008, 04:13 AM
  2. Problem with pointers to dynamic objects
    By mike_g in forum C++ Programming
    Replies: 20
    Last Post: 04-25-2007, 01:16 PM
  3. Replies: 4
    Last Post: 11-02-2006, 10:41 AM
  4. dynamic array of objects
    By mrukok in forum C++ Programming
    Replies: 7
    Last Post: 03-30-2003, 08:35 AM
  5. Dynamic list of Objects in External File
    By TechWins in forum C++ Programming
    Replies: 3
    Last Post: 12-18-2002, 01:05 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21