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..!

bool updateListElement(Object* air)
{
     list <Object>::iterator iObject;
     for (iObject= list.begin(); iObject != list.end(); ++iObject)
     {
        Object temp = *iObject;
        if (temp.getCode() == air->getCode())
        {
            temp=*air;
            return true;
        }
     }
     return false;
}

Recommended Answers

All 2 Replies

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:

bool updateListElement(Object* air)
{
    std::list <Object>::iterator iObject;
     for (iObject= list.begin(); iObject != list.end(); ++iObject)
     {
        Object temp = *iObject;
        if (temp.getCode() == air->getCode())
        {
            *iObject = *air;
            return true;
        }
     }
     return false;
}

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++....!!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.