diff --git a/include/boost/histogram/storage_adaptor.hpp b/include/boost/histogram/storage_adaptor.hpp index 40383cb4..563bdeda 100644 --- a/include/boost/histogram/storage_adaptor.hpp +++ b/include/boost/histogram/storage_adaptor.hpp @@ -171,8 +171,9 @@ struct map_impl : T { if (it != static_cast(map)->end()) { it->second += u; } else { - auto pair = map->emplace(idx, value_type{}); - pair.first->second += u; + value_type tmp{}; + tmp += u; + if (!(tmp == value_type{})) map->emplace(idx, tmp); } return *this; } @@ -184,8 +185,9 @@ struct map_impl : T { if (it != static_cast(map)->end()) { it->second -= u; } else { - auto pair = map->emplace(idx, value_type{}); - pair.first->second -= u; + value_type tmp{}; + tmp -= u; + if (!(tmp == value_type{})) map->emplace(idx, tmp); } return *this; } diff --git a/test/storage_adaptor_test.cpp b/test/storage_adaptor_test.cpp index 88ac2b8f..a2533bc3 100644 --- a/test/storage_adaptor_test.cpp +++ b/test/storage_adaptor_test.cpp @@ -211,6 +211,23 @@ int main() { BOOST_TEST(std::isnan(static_cast(a[1]))); } + // adding or subtracting zero must not create cells in map-based storage_adaptor + { + using map_t = std::map; + auto a = storage_adaptor(); + a.reset(4); + a[0] += 0; + a[1] -= 0; + BOOST_TEST_EQ(static_cast(a).size(), 0); + BOOST_TEST_EQ(a[0], 0); + BOOST_TEST_EQ(a[1], 0); + a[2] += 1; + a[3] -= 1; + BOOST_TEST_EQ(static_cast(a).size(), 2); + BOOST_TEST_EQ(a[2], 1); + BOOST_TEST_EQ(a[3], -1); + } + // with accumulators::weighted_sum { auto a = storage_adaptor>>();