Stan
Stan

Reputation: 38255

Boost Bimap to insert_or_modify

STL map "[]" operator can insert new entries or modify existing entries.

map<string, string> myMap;
myMap["key1"] = "value1";
myMap["key1"] = "value2";

I am rewriting some code with boost::bimap which was implemented by STL map. Is there an easy way to keep the STL "[]" behavior? I found I have to write below 7 lines code to replace the original STL map code (1 line!).

bimap<string, string>::left_iterator itr = myBimap.left.find("key1");
if (itr != myBimap.left.end()) {
    myBimap.left.replace_data(itr, "value2");
} 
else {
    myBimap.insert(bimap<string, string>::value_type("key1", "value2"));
}

I was wondering if there's an utility function like boost::bimap::insert_or_modify().

Upvotes: 5

Views: 2784

Answers (1)

TemplateRex
TemplateRex

Reputation: 70526

The Boost.Bimap documentation shows how mimic a std::map including its operator[] by using set_of and list_of for the bimap template arguments:

#include <iostream>
#include <string>
#include <boost/bimap.hpp>
#include <boost/bimap/set_of.hpp>
#include <boost/bimap/list_of.hpp>

int main()
{
    using namespace std;    
    map<string, string> myMap;
    myMap["key1"] = "value1";
    myMap["key1"] = "value2";
    for (auto&& elem : myMap)
        std::cout << "{" << elem.first << ", " << elem.second << "}, ";
    std::cout << "\n";

    using namespace boost::bimaps;
    bimap<set_of<string>, list_of<string>> myMap2;
    myMap2.left["key1"] = "value1";
    myMap2.left["key1"] = "value2";
    for (auto&& elem : myMap2.left)
        std::cout << "{" << elem.first << ", " << elem.second << "}, ";
    std::cout << "\n";

    auto res1 = myMap2.left.find("key1");
    std::cout << "{" << res1->first << ", " << res1->second << "} \n";    
}

Live Example.

UPDATE: the above code also allows left-searches. However, a right-search is not possible in combination with the required operator[] syntax. The reason is that operator[] modifications can only be done with a mutable right-view (such list_of or vector_of). OTOH, right-searches can only be done from immutable set_of and unordered_set_of and their multi- cousins.

Upvotes: 5

Related Questions