0

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

4
  • What's stopping your from the good ole' for(int x=0; x<m_joystickValues.size(); x++)? Commented Jul 30, 2014 at 23:07
  • 2
    If possible, change to std::vector<std::pair<Vector2D, Vector2D>> m_joystickValues; to have automatic memory management. Commented Jul 30, 2014 at 23:07
  • Use std::shared_ptr<Vector2D> and std::make_shared<Vector2D>() so there's no need for manual memory management. Commented Jul 30, 2014 at 23:22
  • 1
    Which part of writing a for loop are you having trouble with? Have you looked back at your textbook to remind yourself how they work? Commented Jul 30, 2014 at 23:24

3 Answers 3

4

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.

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

1 Comment

The iterator version is missing :-) (with std::vector<std::pair<Vector2D*, Vector2D*>>::iterator instead of auto ^^)
1
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.

Comments

1
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());

2 Comments

You may use m_joystickValues.clear(); instead of erase the whole range
@Jarod42 yes that's neater.

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.