Key and map value exchange in C ++

I am looking for a function in C ++ that replaces the contents of a map ... that is: those that were keys now become elements and those that were now elements. Can you tell me if there is anything in this matter?

+7
source share
4 answers

As Jeffroy said, std::map does not allow this behavior. However, you might want to use the STL-like container Boost.Bimap - a bilinear map.

A Bimap is a data structure that represents a bi-directional relationship between elements of two collections. The container is designed to work as two opposite STL cards. The bimap between collection X and set Y can be considered as a map from X to Y (this representation will be called the left map representation) or as a map from Y to X (called the correct map type).

+13
source

There is no standard method / way to do this, you have to write your own function.

This is not very difficult to do, but first think about it differently.

If you need to invert your key / values, then you can be wrong, but you do not save the logic of the container.

If you need more information, explain why you want to do this.

+1
source

Insert the elements on the map into the multimag - the first value, the second with the corresponding comparison function, which compares the two values ​​of the original map. After all elements with key values ​​are inserted, the multimedia will be sorted by purpose. The task is completed!

+1
source
 template <class T1, class T2> map<T2, T1> swapPairs(map<T1, T2> m) { map<T2, T1> m1; for (auto&& item : m) { m1.emplace(item.second, item.first); } return m1; }; int main() { map<string, int> m; m.emplace("111",5); cout << m.at("111") << endl; // 5 map<int,string> m1 = swapPairs(m); cout << m1.at(5) << endl; // 111 return 0; } 
+1
source

All Articles