4

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

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

我正在用 STL map 实现的 boost::bimap 重写一些代码。有没有一种简单的方法来保持 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"));
}

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

4

1 回答 1

4

Boost.Bimap 文档显示了如何通过使用和为模板参数来模拟std::map包含它的a :operator[]set_oflist_ofbimap

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

活生生的例子。

更新:上面的代码也允许左搜索。但是,不可能结合所需的operator[]语法进行右搜索。原因是operator[]只能使用可变的右视图(例如list_ofvector_of)进行修改。OTOH,只能从不可变 set_of及其unordered_set_of多表亲中进行右搜索。

于 2014-07-07T10:09:52.467 回答