C++ for each, pulling from vector elements

前端 未结 4 1546
长情又很酷
长情又很酷 2020-12-23 15:39

I am trying to do a foreach on a vector of attacks, each attack has a unique ID say, 1-3.

The class method takes the keyboard input of 1-3.

4条回答
  •  再見小時候
    2020-12-23 16:22

    For next examples assumed that you use C++11. Example with ranged-based for loops:

    for (auto &attack : m_attack) // access by reference to avoid copying
    {  
        if (attack->m_num == input)
        {
            attack->makeDamage();
        }
    }
    

    You should use const auto &attack depending on the behavior of makeDamage().

    You can use std::for_each from standard library + lambdas:

    std::for_each(m_attack.begin(), m_attack.end(),
            [](Attack * attack)
            {
                if (attack->m_num == input)
                {
                    attack->makeDamage();
                }
            }
    );
    

    If you are uncomfortable using std::for_each, you can loop over m_attack using iterators:

    for (auto attack = m_attack.begin(); attack != m_attack.end(); ++attack)
    {  
        if (attack->m_num == input)
        {
            attack->makeDamage();
        }
    }
    

    Use m_attack.cbegin() and m_attack.cend() to get const iterators.

提交回复
热议问题