// ======== Begin Code ========

/*
 * enumStringPair.cpp
 *
 *  Created on: 21/10/2010
 *      Author: hills
 */
 
#include <iostream>
#include <string>
#include <map>
 
template <typename _Key, typename _Tp, typename _Compare = std::less< _Key >,
  typename _Alloc = std::allocator< std::pair< const _Key, _Tp> > >
class bimap
 : public std::map< _Key, _Tp, _Compare, _Alloc >
{
 public:
   typedef std::map< _Key, _Tp, _Compare, _Alloc > stdMap;
 
   bimap() : stdMap() {}
   bimap( const bimap &__bm) : stdMap( __bm) {}
   template<typename _InputIterator>
   bimap( _InputIterator __first, _InputIterator __last) : stdMap( __first, __last) {}
 
   _Tp& operator[]( const _Key &__k) { return stdMap::operator[]( __k);}
   _Tp  operator[]( const _Key &__k) const
   {
     return stdMap::at( __k);
   }
   _Key operator[]( const _Tp  &__t) const
   {
     for ( typename stdMap::const_iterator iter = stdMap::begin();
       iter != stdMap::end(); ++iter)
     {
       if ( iter->second == __t) {
         return iter->first;
       }
     }
     throw "bimap::operator[Tp] - Tp not found."; // Throw something. We can't find the mapped data.
   }
};
 
enum MyDataEnum {
  FRED,
  MARY,
  JAMES,
  LISA,
  SAM,
  PENNY
};
 
typedef std::pair< int, std::string> EnumString;
const EnumString myDataPairs[] = {
  EnumString(  FRED,  "Fred Nerk"),
  EnumString(  MARY,  "Mary Carey"),
  EnumString(  JAMES, "James Bond"),
  EnumString(  LISA,  "Lisa Simpson"),
  EnumString(  SAM,   "Sam Iam")
};
const int sizeOfMyDataPairs = sizeof( myDataPairs) / sizeof( std::pair< std::string, int>);
 
typedef bimap< int, std::string> MyDataMap;
const MyDataMap myDataMap( &myDataPairs[0], &myDataPairs[ sizeOfMyDataPairs]);
 
using namespace std;
 
int main( int argc, char *argv[])
{
  try {
    myDataMap[ PENNY] = "Penny Lane"; // This should throw an error because myDataMap is "const".
  }
  catch (...) {
    cout << "Yep, as expect we can add \"Penny Lane\"." << endl;
  }
 
  cout << "List size = " << myDataMap.size() << endl;
  cout << "JAMES = " << myDataMap["James Bond"] << ", " << myDataMap[ JAMES] << endl;
 
  try {
    cout << "PENNY = " << myDataMap[ "Penny Lane"] << endl;
  }
  catch (...) {
    cout << "Yep, as expect \"Penny Lane\" was not there." << endl;
  }
 
  return 0;
}

http://www.codeproject.com/KB/stl/bimap.aspx?fid=12042&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=151#xx0xx

 

g++ --std=c++0x map.cpp -o map.exe
[test]$ ./map.exe
Yep, as expect we can add "Penny Lane".
List size = 5
JAMES = 2, James Bond
Yep, as expect "Penny Lane" was not there.

 

 

 

 

arrow
arrow
    全站熱搜

    hedgezzz 發表在 痞客邦 留言(0) 人氣()