1 #ifndef STL_CONTAINER_ADAPTER_HPP_
2 #define STL_CONTAINER_ADAPTER_HPP_
7 #include <boost/python.hpp>
9 // This template started off life at
10 // http://wiki.python.org/moin/boost.python/StlContainers
12 struct IndexError : std::exception
14 explicit IndexError(): std::exception() {};
17 void translate_index_error(IndexError const &e);
23 typedef typename T::value_type V;
24 typedef typename T::reference R;
25 typedef typename T::const_reference CR;
27 static R get(T& x, int i)
29 if( i<0 ) i+=x.size();
30 if( i>=0 && i<x.size() ) return x[i];
33 static CR get_const(T& x, int i)
35 if( i<0 ) i+=x.size();
36 if( i>=0 && i<x.size() ) return x[i];
39 static void set(T& x, int i, V const& v)
41 if( i<0 ) i+=x.size();
42 if( i>=0 && i<x.size() ) x[i]=v;
43 else throw IndexError();
45 static void del(T& x, int i)
47 if( i<0 ) i+=x.size();
48 if( i>=0 && i<x.size() ) {
49 typename T::iterator itor = x.begin();
52 } else throw IndexError();
54 static void add(T& x, V& v)
58 static bool in(T const& x, V const& v)
60 return std::find(x.begin(), x.end(), v) != x.end();
62 static int index(T const& x, V const& v)
65 for(typename T::const_iterator it=x.begin; it!=x.end(); ++it,++i)
66 if( *it == v ) return i;
71 struct KeyError : std::exception
74 explicit KeyError(): std::exception() {};
77 void translate_key_error(KeyError const &e);
82 typedef typename T::key_type K;
83 typedef typename T::mapped_type V;
84 static V& get(T & x, K const& i)
86 if( x.find(i) != x.end() ) return x[i];
89 static void set(T & x, K const& i, V const& v)
91 x[i]=v; // use map autocreation feature
93 static void del(T & x, K const& i)
95 if( x.find(i) != x.end() ) x.erase(i);
96 else throw KeyError();
98 static bool in(T const& x, K const& i)
100 return x.find(i) != x.end();
102 static boost::python::list keys(T const& x)
104 boost::python::list t;
105 for(typename T::const_iterator it=x.begin(); it!=x.end(); ++it)
109 static boost::python::list values(T const& x)
111 boost::python::list t;
112 for(typename T::const_iterator it=x.begin(); it!=x.end(); ++it)
113 t.append(it->second);
116 static boost::python::list items(T const& x)
118 boost::python::list t;
119 for(typename T::const_iterator it=x.begin(); it!=x.end(); ++it)
120 t.append(boost::python::make_tuple(it->first,it->second));
123 static int index(T const& x, K const& k)
126 for(typename T::const_iterator it=x.begin(); it!=x.end(); ++it,++i)
127 if( it->first == k ) return i;
133 #endif /*STL_CONTAINER_ADAPTER_HPP_*/