【问题标题】:How to modify objects using an iterator? using <list>如何使用迭代器修改对象?使用 <列表>
【发布时间】:2011-12-28 22:49:16
【问题描述】:

所以这里有一个例子。星号的mLocationmSpeedVector3 自定义类型。

我试过了:

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

直接使用iStar-&gt; 不适用于我的运营商,不知道为什么。 那么这样做的正确方法是什么?

   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);
       }
   }

【问题讨论】:

    标签: c++ list iterator


    【解决方案1】:
    std::list<Star>::const_iterator iStar;
    

    您不能通过const_iterator 修改容器中的对象。如果要修改对象,则需要使用iterator(即std::list&lt;Star&gt;::iterator)。

    【讨论】:

    • 然后你怎么做呢?你能用 Star &star = *iStar;还是有更好的方法?
    • 当然,您可以使用对元素的引用。或者您可以在每次需要时通过迭代器访问该元素。
    【解决方案2】:

    正如 James 告诉您的,您应该使用 std::list&lt;Star&gt;::iterator,以便您可以通过调用方法或访问其成员变量来修改对象。

    应该是这样的:

    void UniverseManager::ApplySpeedVector()
    {
        std::list <Star>::iterator iStar;
    
        for (iStar = mStars.begin(); iStar != mStars.end(); ++iStar)
        {
            iStar->SetLocationData(iStar->mLocation += iStar->mSpeed);
        }
    }
    

    不过,如果您想改进您的代码,您可能更喜欢使用 getter 来访问位置和速度:

    void UniverseManager::ApplySpeedVector()
    {
        std::list <Star>::iterator iStar;
    
        for (iStar = mStars.begin(); iStar != mStars.end(); ++iStar)
        {
            iStar->SetLocationData(iStar->GetLocationData() + iStar->GetSpeed());
        }
    }
    

    在任何情况下,您都必须使用非常量迭代器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多