Boost::bimap

來源:互聯網
上載者:User

Boost.Bimap 是一個C++的雙向 map 庫。使用 Boost.Bimap,你可以建立兩個類型都可用作索引值的關聯容器。bimap<X,Y> 可以被視為 std::map<X,Y> 加上 std::map<Y,X>。如果你知道如何使用標準容器,那麼 bimap 的學習曲線就幾乎是平的。在 Boost.Bimap 中作出了大量的努力,以符合STL的命名規則。本庫是按照與常見STL容器相匹配的方式進行設計的。

記住,bm 可單獨用作關係的 set。我們可以插入元素,或者使用該視圖進行遍曆。

 

boost::bimap - 雙向映射

定義一個 bimap :

#include bimap bm;

它有3個不同的視圖:

bm.left : 是一個相容於 std::map 類型的東西.

bm.right: 是一個相容於 std:::map 類型的東西.

bm 是一個相容於 std::set< relation 類型的東西.

 例如我們有一個輸出map的函數如下:

template< class MapType > void print_map(const MapType & m)

{

      typedef typename MapType::const_iterator const_iterator;

     for( const_iterator iter = m.begin(), iend = m.end(); iter != iend; ++iter )

      {

         std::cout << iter->first << "-->" << iter->second << std::endl;

       }

}

它的參數可以接受一個 std::map 對象. 所以它也可以接受如下調用:

print_map( bm.left );

print_map( bm.right );

下邊我們定義一個整數和字串的雙向映射: 

typedef boost::bimap< int, std::string > bm_type;

 bm_type bm;

向其插入資料:

bm.insert( bm_type::value_type(1, "one" ) );

bm.insert( bm_type::value_type(2, "two" ) );

 輸出剛才插入的資料:

 std::cout << "There are " << bm.size() << "relations" << std::endl; for( bm_type::const_iterator iter = bm.begin(), iend = bm.end(); iter != iend; ++iter )

 {

 std::cout << iter->left << " <--> " << iter->right << std::endl;

 }

接著我們使用它的 left 視圖(就像在使用一個std::map): //left視圖的迭代器類型

 typedef bm_type::left_map::const_iterator left_const_iterator;

for( left_const_iterator left_iter = bm.left.begin(), iend = bm.left.end(); left_iter != iend; ++left_iter )

{

   std::cout << left_iter->first << " --> " << left_iter->second << std::endl;

}

bm_type::left_const_iterator left_iter = bm.left.find(2);

assert( left_iter->second == "two" ); // 再通過左視圖向 bm 插入資料 //

它和直接用 bm.insert( bm_type::value_type(3,"three") ); 效果一樣

bm.left.insert( bm_type::left_value_type( 3, "three" ) );

同樣的. 我們可以使用它的 right視圖 : // 通過 string 尋找

bm_type::right_const_iterator right_iter = bm.right.find("two"); assert( right_iter->second == 2 ); // 調用 at() assert( bm.right.at("one") == 1 ); // 刪除 "two" 對應的關係 bm.right.erase("two");

 最後. 預設時在 std::map 中. 我們插入 ("1", 1) 後再插入 ("one", 1) 是可以的.

但這在bimap中不行. 因為它左右兩個都可以做索引值. 要求它們兩者都必須是唯一的. 但這隻是它預設時的樣子. bimap可以通過模板參數來定製它一些特徵: 例如可以指定是否需要 一對多 的映射關係: 可以一個 x 對應多個 y. 可以多個 x 對應一個 y. 也可以多個 x 對應多個 y. 還可以指定是否要求 left視圖 或 right視圖 或 兩者 有序. 如果不要求有序的話. 它可以用 hash表來實現底層.

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.