Creating a template for working with std :: map and std :: unordered_map

I have the following template function that returns a copy of this map with the changed keys and values:

template<typename M> auto swapKeysAndValues(const M& m) { std::map<typename M::mapped_type, typename M::key_type> swapped; for (auto& p : m) { swapped.emplace(p.second, p.first); } return swapped; } 

Is there a way to make the template above for std::map and std::unordered_map ? That is, for std::map<K, V> it should return std::map<V, K> , and for std::unordered_map<K, V> it should return std::unordered_map<V, K> .

+5
source share
2 answers
 template<template <typename...> class Map, typename K, typename V> auto swapKeyValues(const Map<K, V>& map) { Map<V, K> result; for (const auto& p : map) result.emplace(p.second, p.first); return result; } 

Living example

+4
source

There are several answers here, so I'm not going to cover the old lands.

However, there is one aspect of this that you should carefully consider.

unordered maps do not match the maps - they have a requirement for a hash function for the key (in addition to the equality predicate). As we have seen, it is trivial to write a template function that accepts default values, but is that what you want?

If your K and V have hash functions, then they are already keys. In this case, you really do not want boost::bimap or boost::multi_index_map ?

+1
source

Source: https://habr.com/ru/post/1234425/


All Articles