DRY: simpler removal of element from middle of std::vector

This commit is contained in:
Andrew Meadows 2018-04-03 18:28:07 -07:00
parent 0a2b4a8d1d
commit bd2bfb6807
2 changed files with 17 additions and 18 deletions

View file

@ -79,20 +79,14 @@ void PhysicalEntitySimulation::removeOwnershipData(EntityMotionState* motionStat
for (uint32_t i = 0; i < _owned.size(); ++i) {
if (_owned[i] == motionState) {
_owned[i]->clearOwnershipState();
if (i < _owned.size() - 1) {
_owned[i] = _owned.back();
}
_owned.pop_back();
_owned.remove(i);
}
}
} else if (motionState->getOwnershipState() == EntityMotionState::OwnershipState::PendingBid) {
for (uint32_t i = 0; i < _bids.size(); ++i) {
if (_bids[i] == motionState) {
_bids[i]->clearOwnershipState();
if (i < _bids.size() - 1) {
_bids[i] = _bids.back();
}
_bids.pop_back();
_bids.remove(i);
}
}
}
@ -368,10 +362,7 @@ void PhysicalEntitySimulation::sendOwnershipBids(uint32_t numSubsteps) {
_bids[i]->clearOwnershipState();
}
if (removeBid) {
if (i < _bids.size() - 1) {
_bids[i] = _bids.back();
}
_bids.pop_back();
_bids.remove(i);
} else {
if (now > _bids[i]->getNextBidExpiry()) {
_bids[i]->sendBid(_entityPacketSender, numSubsteps);
@ -393,10 +384,7 @@ void PhysicalEntitySimulation::sendOwnedUpdates(uint32_t numSubsteps) {
} else {
_owned[i]->clearOwnershipState();
}
if (i < _owned.size() - 1) {
_owned[i] = _owned.back();
}
_owned.pop_back();
_owned.remove(i);
} else {
if (_owned[i]->shouldSendUpdate(numSubsteps)) {
_owned[i]->sendUpdate(_entityPacketSender, numSubsteps);

View file

@ -27,6 +27,17 @@ class PhysicalEntitySimulation;
using PhysicalEntitySimulationPointer = std::shared_ptr<PhysicalEntitySimulation>;
using SetOfEntityMotionStates = QSet<EntityMotionState*>;
class VectorOfEntityMotionStates: public std::vector<EntityMotionState*> {
public:
void remove(uint32_t index) {
assert(index < size());
if (index < size() - 1) {
(*this)[index] = back();
}
pop_back();
}
};
class PhysicalEntitySimulation : public EntitySimulation {
Q_OBJECT
public:
@ -89,8 +100,8 @@ private:
PhysicsEnginePointer _physicsEngine = nullptr;
EntityEditPacketSender* _entityPacketSender = nullptr;
std::vector<EntityMotionState*> _owned;
std::vector<EntityMotionState*> _bids;
VectorOfEntityMotionStates _owned;
VectorOfEntityMotionStates _bids;
uint64_t _nextBidExpiry;
uint32_t _lastStepSendPackets { 0 };
};