myMap; myMap["k...">

Boost Bimap for insert_or_modify

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

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

I am rewriting code with boost :: bimap, which was implemented using an STL card. Is there an easy way to keep the STL behavior "[]"? I found that I need to write below 7 lines of code in order to replace the source code of the STL card (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 is a utility function like boost :: bimap :: insert_or_modify ().

+4
source share
1 answer

Boost.Bimap documentation shows how to simulatestd::map, includingoperator[]usingset_ofandlist_ofthe template argumentsbimap:

#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";    
}

Living example.

UPDATE: . operator[]. , operator[] ( list_of vector_of). OTOH, set_of unordered_set_of .

+4

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


All Articles