[solved] Best practice for iterating through OwnedArray while deleting part of the element

What’s the best way to iterate through an owned array while deleting part of the elements? In the following code it could crash. As I assume the iterator is invalid after one element is deleted:


for (auto s: myOwnedArray)
{
    if (condition is true)
        myOwnedArray.removeObject (s);
}

Thanks in advance!

for (int i=myOwnedArray.size()-1; i!=-1; --i)
{
    auto s = myOwnedArray.getUnchecked(i);
    if (condition is true)
    {
         myOwnedArray.remove(i);
    }

}
1 Like

For some weird reason I prefer

for (int i = myOwnedArray.size()-1; i >= 0; --i)
2 Likes

It’s safer if you manipulate “i” inside the loop. I prefer the first way because it’s easier to type with my keyboard.

I got rid of my German keyboard for that reason. All brackets are in awkward positions there.

But I wouldn’t let my keyboard decide over my code /rant over.