From 9c8187bd29170678675b1d6482e012116202add7 Mon Sep 17 00:00:00 2001 From: cameel Date: Wed, 29 Jan 2020 17:37:10 +0100 Subject: [PATCH] CommonData: Add invertMap() function --- libsolutil/CommonData.h | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/libsolutil/CommonData.h b/libsolutil/CommonData.h index c7c9d80e3..45f19bcb5 100644 --- a/libsolutil/CommonData.h +++ b/libsolutil/CommonData.h @@ -156,6 +156,23 @@ T convertContainer(U&& _from) }; } +/// Gets a @a K -> @a V map and returns a map where values from the original map are keys and keys +/// from the original map are values. +/// +/// @pre @a originalMap must have unique values. +template +std::map invertMap(std::map const& originalMap) +{ + std::map inverseMap; + for (auto const& [key, value]: originalMap) + { + assert(inverseMap.count(value) == 0); + inverseMap.insert({value, key}); + } + + return inverseMap; +} + // String conversion functions, mainly to/from hex/nibble/byte representations. enum class WhenError