diff options
author | Jacques Lucke <jacques@blender.org> | 2020-04-28 14:55:36 +0300 |
---|---|---|
committer | Jacques Lucke <jacques@blender.org> | 2020-04-28 14:55:36 +0300 |
commit | 9c65ac73112f1a0f837cb50a2a446129acf19081 (patch) | |
tree | 7ef58bff4aeae04e8dafde734ca5e2b5ac0f99e1 | |
parent | 2c6022108070b53f0293aaba177bc63d184161c7 (diff) |
BLI: add Map.lookup_or_add_default method
-rw-r--r-- | source/blender/blenlib/BLI_map.hh | 13 | ||||
-rw-r--r-- | tests/gtests/blenlib/BLI_map_test.cc | 11 |
2 files changed, 24 insertions, 0 deletions
diff --git a/source/blender/blenlib/BLI_map.hh b/source/blender/blenlib/BLI_map.hh index eb9c6372995..ea5e5da4099 100644 --- a/source/blender/blenlib/BLI_map.hh +++ b/source/blender/blenlib/BLI_map.hh @@ -408,6 +408,19 @@ class Map { } /** + * Return the value that corresponds to the given key. + * If it does not exist yet, insert a new default constructed value and return that. + */ + ValueT &lookup_or_add_default(const KeyT &key) + { + return this->lookup_or_add(key, []() { return ValueT(); }); + } + ValueT &lookup_or_add_default(const KeyT &&key) + { + return this->lookup_or_add(std::move(key), []() { return ValueT(); }); + } + + /** * Get the number of elements in the map. */ uint32_t size() const diff --git a/tests/gtests/blenlib/BLI_map_test.cc b/tests/gtests/blenlib/BLI_map_test.cc index e9e4b1895ab..5a19216fa7c 100644 --- a/tests/gtests/blenlib/BLI_map_test.cc +++ b/tests/gtests/blenlib/BLI_map_test.cc @@ -213,6 +213,17 @@ TEST(map, AddOverride) EXPECT_EQ(map.lookup(3), 7.0f); } +TEST(map, LookupOrAddDefault) +{ + IntFloatMap map; + map.lookup_or_add_default(3) = 6; + EXPECT_EQ(map.lookup(3), 6); + map.lookup_or_add_default(5) = 2; + EXPECT_EQ(map.lookup(5), 2); + map.lookup_or_add_default(3) += 4; + EXPECT_EQ(map.lookup(3), 10); +} + TEST(map, MoveConstructorSmall) { IntFloatMap map1; |