944,030 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 2300
  • C++ RSS
Oct 22nd, 2009
0

Update element in list

Expand Post »
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..!

c++ Syntax (Toggle Plain Text)
  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. }
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
eliza2044 is offline Offline
22 posts
since May 2009
Oct 22nd, 2009
1
Re: Update element in list
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:
C++ Syntax (Toggle Plain Text)
  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. }
Reputation Points: 1446
Solved Threads: 135
Practically a Master Poster
Tom Gunn is offline Offline
681 posts
since Jun 2009
Oct 22nd, 2009
0
Re: Update element in list
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++....!!!!
Reputation Points: 10
Solved Threads: 0
Newbie Poster
eliza2044 is offline Offline
22 posts
since May 2009

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Object's value turn into -858993460?
Next Thread in C++ Forum Timeline: Sorting





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC