In this C++11 solution all map items are kept in constexpr
array and there are constexpr
recursive functions to search by either key or value.
#include <utility>
using Item = std::pair<int, int>;
constexpr Item map_items[] = {
{ 6, 7 },
{ 10, 12 },
{ 300, 5000 },
};
constexpr auto map_size = sizeof map_items/sizeof map_items[0];
static constexpr int findValue(int key, int range = map_size) {
return
(range == 0) ? throw "Key not present":
(map_items[range - 1].first == key) ? map_items[range - 1].second:
findValue(key, range - 1);
};
static constexpr int findKey(int value, int range = map_size) {
return
(range == 0) ? throw "Value not present":
(map_items[range - 1].second == value) ? map_items[range - 1].first:
findKey(value, range - 1);
};
static_assert(findKey(findValue(10)) == 10, "should be inverse");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…