3

So here's an example. The star's mLocation and mSpeed are a Vector3 custom type.

I'v tried:

Star &star = *iStar;
Star star = *iStar;

Using iStar-> directly doesn't work with my operators, not sure why. So whats the proper way to do that?

   void UniverseManager::ApplySpeedVector()
   { 
   std::list <Star>::const_iterator iStar;

       for (iStar = mStars.begin(); iStar != mStars.end(); ++iStar)
       {
           // how to I get a hold on the object the iterator is pointing to so I can modify its values
                   // i tried  Star &star = *iStar;  this is illegal
                   // tried just using the iStar->mLocation += iStar->mSpeed this also fails due to the operator not accepting the values not sure why
                   // tried other things as well, so what is the proper way to do this?

           iStar->SetLocationData( iStar->mLocation += iStar->mSpeed);
       }
   }

2 Answers 2

11
std::list<Star>::const_iterator iStar;

You cannot modify the objects in a container via a const_iterator. If you want to modify the objects, you need to use an iterator (i.e., std::list<Star>::iterator).

Sign up to request clarification or add additional context in comments.

2 Comments

and then how do you go about it? Can you use Star &star = *iStar; or is there a better way?
Sure, you can use a reference to the element. Or you can access the element through the iterator each time you need it.
3

As James told you, you should use a std::list<Star>::iterator so that you can modify the object by calling a method or accessing its member variables.

It would be something like this:

void UniverseManager::ApplySpeedVector()
{
    std::list <Star>::iterator iStar;

    for (iStar = mStars.begin(); iStar != mStars.end(); ++iStar)
    {
        iStar->SetLocationData(iStar->mLocation += iStar->mSpeed);
    }
}

Nevertheless, if you want to improve your code you might prefer to have a getter for accessing the location and the speed:

void UniverseManager::ApplySpeedVector()
{
    std::list <Star>::iterator iStar;

    for (iStar = mStars.begin(); iStar != mStars.end(); ++iStar)
    {
        iStar->SetLocationData(iStar->GetLocationData() + iStar->GetSpeed());
    }
}

In any case, you have to use a non-const iterator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.