Skip to content

How to use

Julijan Šribar edited this page Jan 7, 2018 · 5 revisions

Below is a code sample that illustrates usage of all interface members. There are two specializations of the bidirectional map: BidirectionalMap which uses std::map internally and BidirectionalUnorderedMap which uses std::unordered_map internally. Interface for both specializations is the same, but BidirectionalUnorderedMap is generally faster.

You may find more detailed specification of methods by looking at unit tests which (hopefully) cover all functionality.

To use classes, simply include BidirectionalMap.h header. Classes are defined in MapSpecial namespace.

#include "BidirectionalMap.h"

using namespace MapSpecial;

BidirectionalUnorderedMap<int, std::string> bum;

bum.Insert(1, "Dora"); // insert a new pair of values
bum.Insert(2, "Matej"); // insert a new pair of values

std::cout << "[2]=" << bum[2].c_str() << std::endl; // output second value paired with first value 2
std::cout << "[\"Dora\"]=" << bum["Dora"] << std::endl; // output first value paired with second value "Dora"

bum.ChangeFirst(3, "Matej"); // change the first value in an existing pair that has second value "Matej"
bum.ChangeSecond(1, "Vedran"); // change the second value in an existing pair that has first value 1

bum.Remove("Vedran"); // remove pair that has second value "Vedran"
bum.Remove(3); // remove pair that has first value 3

bum.Insert(3, "Vedran");

std::cout << "Exists(3)=" << bum.FirstExists(3) << std::endl; // check that a pair with value 3 exists
std::cout << "Exists(\"Dora\")=" << bum.SecondExists("Dora") << std::endl; // check that a pair with value "Dora" exists

std::cout << "Size()=" << bum.Size() << std::endl; // output the number of pairs

bum.Clear(); // clear the container

Note: operator [] will throw std::out_of_range exception if corresponding pair doesn't exist.

For bidirectional map that has both keys of the same type, the interface is reduced. Operator [] and Exists and Remove methods work for first key only. Consequently, to access values by second key you need to use explicit methods AtSecond, SecondExists and RemoveSecond:

BidirectionalMap<std::string, std::string> bm;

bm.Insert("Roof", "Dach"); // insert a new pair
bm.Insert("Home", "Heim"); // insert a new pair

std::cout << "[\"Home\"]=" << bm["Home"].c_str() << std::endl; // output second value paired with "Home"

bm.ChangeSecond("Home", "Haus"); // change the second value in an existing pair that has first value "Home"

bm.RemoveFirst("Roof"); // remove pair that has first value "Roof"

bm.Insert("Car", "Auto");

std::cout << "FirstExists(\"Car\")=" << bm.FirstExists("Car") << std::endl; // check that a pair with first value "Car" exists
std::cout << "SecondExists(\"Auto\")=" << bm.SecondExists("Auto") << std::endl; // check that a pair with second value "Auto" exists

Clone this wiki locally