westiti
westiti

Reputation: 35

iterate through vector with for loop in c++

I am reading a tutorial about joystick input handling with SDL and I am struggling with a part of the code.

In .h file I got:

std::vector<std::pair<Vector2D*, Vector2D*> > m_joystickValues;

and in .cpp file I got:

m_joystickValues.push_back(std::make_pair(new Vector2D(0,0),new Vector2D(0,0)));

In this case I have one joystick, if there is many joysticks there will more push_backs, I want to access the adresses in "m_joystickValues" so I can delete them in a clean function.

Anyone has an idea how I can do this with a for loop. Thanks

Upvotes: 0

Views: 467

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

For example you can use the range-based for statement

for ( auto &p : m_joystickValues )
{
   delete p.first;
   delete p.second;
}

The same can be done using the ordinary for statement

for ( size_t i = 0; i < m_joystickValues.size(); i++ )
{
   delete m_joystickValues[i].first;
   delete m_joystickValues[i].second;
}

Or you can use standard algorithm std::for_each with an appropriate lambda-expression. It is similar to using a for statement with iterators.

Upvotes: 4

jazaman
jazaman

Reputation: 1019

for(auto& i : m_joystickValues)
{
    delete i.second;
    delete i.first; // or do whatever
}

At end of the loop you can erase the entire vector

m_joystickValues.erase(m_joystickValues.begin(), m_joystickValues.end());

Upvotes: 1

Franko Leon Tokalić
Franko Leon Tokalić

Reputation: 1508

for(int i = 0; i < m_joystickValues.size(); i++)
{
    m_joystickValues[i] //do something with this
}

Is this what you are looking for? Also, you could use the at function, since it is more safe.

Upvotes: 1

Related Questions