Skip to content

Spatial Containers

Spatial Containers

Spatial container are an extension of sets and maps that allow us to order data according to multiple dimensions. This is particularly useful in games and graphical interfaces, where objects need to be mapped in space. The standard library does not include spatial containers so an external library needs to be used.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Set options to not build pareto examples
# - Cache our own BUILD_EXAMPLES var so that pareto
#   doesn't mess with it
set(BUILD_MATPLOT_TARGETS OFF CACHE BOOL "" FORCE)
set(BUILD_EXAMPLES_PREV ${BUILD_EXAMPLES})
set(BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
FetchContent_Declare(pareto GIT_REPOSITORY https://github.com/alandefreitas/pareto.git GIT_TAG v1.2.0)
FetchContent_MakeAvailable(pareto)
set(BUILD_EXAMPLES ${BUILD_EXAMPLES_PREV} CACHE BOOL "" FORCE)
add_executable(spatial_containers spatial_containers.cpp)
target_link_libraries(spatial_containers PUBLIC pareto)

1
#include <pareto/spatial_map.h>

1
2
3
// Unlike a map<map<...>>, which represents a disjunction of indexes,
// a spatial map represents a conjunction of indexes.
pareto::spatial_map<double, 2, unsigned> m;

1
2
3
4
5
m(-2.5, -1.5) = 17;
m(-2.1, -0.5) = 32;
m(-1.6, 0.9) = 36;
m(-0.6, 0.9) = 13;
m(-0.5, 0.8) = 32;

1
2
3
4
std::cout << "Closest elements to [0, 0]:" << std::endl;
for (auto it = m.find_nearest({0.,0.}, 2); it != m.end(); ++it) {
    std::cout << it->first << ": " << it->second << std::endl;
}

1
2
3
4
std::cout << "Elements between [-1, -1] and [+1, +1]:" << std::endl;
for (auto it = m.find_intersection({-1.,-1.}, {+1, +1}); it != m.end(); ++it) {
    std::cout << it->first << ": " << it->second << std::endl;
}

Share Snippets