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
15 explicit IndexError(): std::exception() {};
18 void translate(IndexError const &e);
24 typedef typename T::value_type V;
25 typedef typename T::reference R;
26 typedef typename T::const_reference CR;
28 static R get(T& x, int i)
30 if( i<0 ) i+=x.size();
31 if( i>=0 && i<x.size() ) return x[i];
34 static CR get_const(T& x, int i)
36 if( i<0 ) i+=x.size();
37 if( i>=0 && i<x.size() ) return x[i];
40 static void set(T& x, int i, V const& v)
42 if( i<0 ) i+=x.size();
43 if( i>=0 && i<x.size() ) x[i]=v;
44 else throw IndexError();
46 static void del(T& x, int i)
48 if( i<0 ) i+=x.size();
49 if( i>=0 && i<x.size() ) {
50 typename T::iterator itor = x.begin();
53 } else throw IndexError();
55 static void add(T& x, V& v)
59 static bool in(T const& x, V const& v)
61 return std::find(x.begin(), x.end(), v) != x.end();
63 static int index(T const& x, V const& v)
66 for(typename T::const_iterator it=x.begin; it!=x.end(); ++it,++i)
67 if( *it == v ) return i;
72 struct KeyError : std::exception
75 explicit KeyError(): std::exception() {};
78 void translate(KeyError const &e);
83 typedef typename T::key_type K;
84 typedef typename T::mapped_type V;
85 static V& get(T const& x, K const& i)
87 if( x.find(i) != x.end() ) return x[i];
90 static void set(T const& x, K const& i, V const& v)
92 x[i]=v; // use map autocreation feature
94 static void del(T const& x, K const& i)
96 if( x.find(i) != x.end() ) x.erase(i);
97 else throw KeyError();
99 static bool in(T const& x, K const& i)
101 return x.find(i) != x.end();
103 static boost::python::list keys(T const& x)
105 boost::python::list t;
106 for(typename T::const_iterator it=x.begin; it!=x.end(); ++it)
110 static boost::python::list values(T const& x)
112 boost::python::list t;
113 for(typename T::const_iterator it=x.begin; it!=x.end(); ++it)
114 t.append(it->second);
117 static boost::python::list items(T const& x)
119 boost::python::list t;
120 for(typename T::const_iterator it=x.begin; it!=x.end(); ++it)
121 t.append(boost::python::make_tuple(it->first,it->second));
124 static int index(T const& x, K const& k)
127 for(typename T::const_iterator it=x.begin; it!=x.end(); ++it,++i)
128 if( it->first == k ) return i;
134 #endif /*STL_CONTAINER_ADAPTER_HPP_*/