Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ have a bijective map type?

Tags:

c++

types

Does C++ have anything which behaves like std::map<T1, T2>, but permitting not only looking for a T1 value to find its associated T2 value, but also to look for a particular T2 value to find its associated T1 value? (Which would mean values on both sides need to be unique.)

like image 527
user149408 Avatar asked Feb 17 '26 15:02

user149408


2 Answers

The C++ standard library doesn't have one, but Boost library's boost::bimap is a data structure that behaves exactly the way you describe.

  • Both sets of elements must be unique
  • Given a container map of type boost::bimap<T1,T2>:
    • map.left provides an interface that closely matches std::map<T1,T2>, including all T1-based lookup
    • map.right provides an interface that closely matches std::map<T2,T1>, including all T2-based lookup
  • Because all elements must be unique, one difference in the interface is that all elements are const. You can add and remove, but you can not modify in-place.
like image 70
Drew Dormann Avatar answered Feb 19 '26 05:02

Drew Dormann


You could do this with boost::bimap from the boost library. Eg.

    boost::bimap<int, std::string> map;
    map.insert({1, "one"});
    map.insert({2, "two"});

    std::cout << map.left.at(1) << "\n";  // "one"
    std::cout << map.right.at("two") << "\n";  // 2
like image 39
Cameron Avatar answered Feb 19 '26 04:02

Cameron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!