将 Bimap 提升为 insert_or_modify

Sta*_*tan 5 c++ boost bimap

STL映射“[]”运算符可以插入新条目或修改现有条目。

map<string, string> myMap;
myMap["key1"] = "value1";
myMap["key1"] = "value2";
Run Code Online (Sandbox Code Playgroud)

我正在用boost::bimap重写一些由STL映射实现的代码。有没有简单的方法来保持STL“[]”行为?我发现我必须编写以下 7 行代码来替换原来的 STL 地图代码(1 行!)。

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"));
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有像 boost::bimap::insert_or_modify() 这样的实用函数。

Tem*_*Rex 5

Boost.Bimap文档展示了如何std::map通过operator[]使用set_oflist_of作为bimap模板参数来模仿 a :

#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";    
}
Run Code Online (Sandbox Code Playgroud)

活生生的例子。

更新:上面的代码还允许左搜索。然而,与所需语法相结合的右搜索是不可能的operator[]。原因是修改只能通过可变的右视图(例如或)operator[]来完成。OTOH,右搜索只能从不可变的和它们的多表兄弟中完成。list_ofvector_of set_ofunordered_set_of