31

**Graphics / Re: Erase only one rectangleShape**

« **on:**July 23, 2022, 04:28:37 pm »

std::remove_if works perfectly for removing all instances which intersect. Here's a CME:

And the output:

template <typename T>

std::ostream& operator << (std::ostream& out, sf::Rectangle<T> r)

{

out << "[ " << r.left << ", " << r.bottom << ", " << r.width << ", " << r.height << " ]";

return out;

}

int main()

{

sf::FloatRect playerBounds = { 0.f, 0.f, 10.f, 10.f };

std::vector<sf::FloatRect> doors =

{

sf::FloatRect(-2.f, 0.f, 10.f, 10.f),

sf::FloatRect(-20.f, 0.f, 10.f, 10.f),

sf::FloatRect(2.f, 0.f, 10.f, 10.f),

sf::FloatRect(0.f, 20.f, 10.f, 10.f),

};

std::cout << "Doors before: " << std::endl;

for (auto door : doors)

{

std::cout << door << std::endl;

}

doors.erase(std::remove_if(doors.begin(), doors.end(),

[playerBounds](const sf::FloatRect& door)

{

return playerBounds.intersects(door);

}), doors.end());

std::cout << "Doors after: " << std::endl;

for (auto door : doors)

{

std::cout << door << std::endl;

}

return 0;

}

std::ostream& operator << (std::ostream& out, sf::Rectangle<T> r)

{

out << "[ " << r.left << ", " << r.bottom << ", " << r.width << ", " << r.height << " ]";

return out;

}

int main()

{

sf::FloatRect playerBounds = { 0.f, 0.f, 10.f, 10.f };

std::vector<sf::FloatRect> doors =

{

sf::FloatRect(-2.f, 0.f, 10.f, 10.f),

sf::FloatRect(-20.f, 0.f, 10.f, 10.f),

sf::FloatRect(2.f, 0.f, 10.f, 10.f),

sf::FloatRect(0.f, 20.f, 10.f, 10.f),

};

std::cout << "Doors before: " << std::endl;

for (auto door : doors)

{

std::cout << door << std::endl;

}

doors.erase(std::remove_if(doors.begin(), doors.end(),

[playerBounds](const sf::FloatRect& door)

{

return playerBounds.intersects(door);

}), doors.end());

std::cout << "Doors after: " << std::endl;

for (auto door : doors)

{

std::cout << door << std::endl;

}

return 0;

}

And the output:

Doors before:

[ -2, 0, 10, 10 ]

[ -20, 0, 10, 10 ]

[ 2, 0, 10, 10 ]

[ 0, 20, 10, 10 ]

Doors after:

[ -20, 0, 10, 10 ]

[ 0, 20, 10, 10 ]

[ -2, 0, 10, 10 ]

[ -20, 0, 10, 10 ]

[ 2, 0, 10, 10 ]

[ 0, 20, 10, 10 ]

Doors after:

[ -20, 0, 10, 10 ]

[ 0, 20, 10, 10 ]