Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature/remove_by_condition #6

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions include/spatial_hash/impl/layer_impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,18 @@ void Layer<BlockT>::removeBlocks(const BlockIndexIterable& block_indices) {
}
}

template <typename BlockT>
void Layer<BlockT>::removeBlocks(const std::function<bool(const BlockT&)>& condition) {
auto it = blocks_.begin();
while (it != blocks_.end()) {
if (condition(*it->second)) {
it = blocks_.erase(it);
} else {
++it;
}
}
}

template <typename BlockT>
void Layer<BlockT>::clear() {
blocks_.clear();
Expand Down
6 changes: 6 additions & 0 deletions include/spatial_hash/layer.h
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,12 @@ class Layer {
template <typename BlockIndexIterable>
void removeBlocks(const BlockIndexIterable& block_indices);

/**
* @brief Remove all blocks that satisfy a given condition.
* @param condition The condition to check. Evaluates to true if the block should be removed.
*/
void removeBlocks(const std::function<bool(const BlockT&)>& condition);

/**
* @brief Remove all blocks from the layer.
*/
Expand Down
22 changes: 22 additions & 0 deletions tests/utest_layer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -204,4 +204,26 @@ TEST(Layer, BlocksWithCondition) {
}
}

TEST(Layer, RemoveBlocksWithCondition) {
struct Block {
int data;
};
Layer<Block> layer(1.0f);
layer.allocateBlock(BlockIndex(0, 0, 0)).data = 1;
layer.allocateBlock(BlockIndex(1, 0, 0)).data = 2;
layer.allocateBlock(BlockIndex(0, 1, 0)).data = 3;
layer.allocateBlock(BlockIndex(0, 0, 1)).data = 4;

// Remove blocks with condition.
const std::function<bool(const Block&)> greater2 = [](const Block& block) {
return block.data > 2;
};
layer.removeBlocks(greater2);
EXPECT_EQ(layer.numBlocks(), 2);
EXPECT_TRUE(layer.hasBlock(BlockIndex(0, 0, 0)));
EXPECT_TRUE(layer.hasBlock(BlockIndex(1, 0, 0)));
EXPECT_FALSE(layer.hasBlock(BlockIndex(0, 1, 0)));
EXPECT_FALSE(layer.hasBlock(BlockIndex(0, 0, 1)));
}

} // namespace spatial_hash