Update element in list

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: May 2009
Posts: 20
Reputation: eliza2044 is an unknown quantity at this point 
Solved Threads: 0
eliza2044 eliza2044 is offline Offline
Newbie Poster

Update element in list

 
0
  #1
Oct 22nd, 2009
Hey guys,

Can anyone post sample code about updating an object that is already in an std::list? I know that it sounds as a really stupid question, but obviously I'm doing something wrong.

In my code I'm going through the list with an iterator until I reach the object of interest. My intention is to replace the current node in the list with another object.

The following snippet of code demonstrates that but I'm sure that I do something wrong in the if statement.

Thanks in advance..!

  1. bool updateListElement(Object* air)
  2. {
  3. list <Object>::iterator iObject;
  4. for (iObject= list.begin(); iObject != list.end(); ++iObject)
  5. {
  6. Object temp = *iObject;
  7. if (temp.getCode() == air->getCode())
  8. {
  9. temp=*air;
  10. return true;
  11. }
  12. }
  13. return false;
  14. }
Reply With Quote Quick reply to this message  
Join Date: Jun 2009
Posts: 681
Reputation: Tom Gunn has much to be proud of Tom Gunn has much to be proud of Tom Gunn has much to be proud of Tom Gunn has much to be proud of Tom Gunn has much to be proud of Tom Gunn has much to be proud of Tom Gunn has much to be proud of Tom Gunn has much to be proud of Tom Gunn has much to be proud of Tom Gunn has much to be proud of 
Solved Threads: 133
Tom Gunn's Avatar
Tom Gunn Tom Gunn is offline Offline
Practically a Master Poster
 
1
  #2
Oct 22nd, 2009
Close, but a temporary copy of the object is still an independent copy. C++ does not make reference copies of objects like Java or C#. To replace the object the iterator refers to, you need to assign to the dereferenced iterator. This will overwrite the object that it refers to:
  1. bool updateListElement(Object* air)
  2. {
  3. std::list <Object>::iterator iObject;
  4. for (iObject= list.begin(); iObject != list.end(); ++iObject)
  5. {
  6. Object temp = *iObject;
  7. if (temp.getCode() == air->getCode())
  8. {
  9. *iObject = *air;
  10. return true;
  11. }
  12. }
  13. return false;
  14. }
-Tommy (For Great Justice!) Gunn
Reply With Quote Quick reply to this message  
Join Date: May 2009
Posts: 20
Reputation: eliza2044 is an unknown quantity at this point 
Solved Threads: 0
eliza2044 eliza2044 is offline Offline
Newbie Poster
 
0
  #3
Oct 22nd, 2009
Thank you very much... I was trying to figure out what was wrong and never thought I had to do it that way!!!

Well thanks, I need to keep that in mind with C++....!!!!
Reply With Quote Quick reply to this message  
Reply

Tags
list, object, update

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC