1 #ifndef STL_CONTAINER_ADAPTER_HPP_
2 #define STL_CONTAINER_ADAPTER_HPP_
5 #include <boost/python.hpp>
7 // This template started off life at
8 // http://wiki.python.org/moin/boost.python/StlContainers
10 void IndexError() { PyErr_SetString(PyExc_IndexError, "Index out of range"); }
14 typedef typename T::value_type V;
15 static V& get(T& x, int i)
17 if( i<0 ) i+=x.size();
18 if( i>=0 && i<x.size() ) return x[i];
21 static void set(T& x, int i, V const& v)
23 if( i<0 ) i+=x.size();
24 if( i>=0 && i<x.size() ) x[i]=v;
27 static void del(T& x, int i)
29 if( i<0 ) i+=x.size();
30 if( i>=0 && i<x.size() ) {
31 typename T::iterator itor = x.begin();
36 static void add(T& x, V& v)
40 static bool in(T const& x, V const& v)
42 return std::find(x.begin(), x.end(), v) != x.end();
44 static int index(T const& x, V const& v)
47 for(typename T::const_iterator it=x.begin; it!=x.end(); ++it,++i)
48 if( *it == v ) return i;
53 void KeyError() { PyErr_SetString(PyExc_KeyError, "Key not found"); }
57 typedef typename T::key_type K;
58 typedef typename T::mapped_type V;
59 static V& get(T const& x, K const& i)
61 if( x.find(i) != x.end() ) return x[i];
64 static void set(T const& x, K const& i, V const& v)
66 x[i]=v; // use map autocreation feature
68 static void del(T const& x, K const& i)
70 if( x.find(i) != x.end() ) x.erase(i);
73 static bool in(T const& x, K const& i)
75 return x.find(i) != x.end();
77 static boost::python::list keys(T const& x)
79 boost::python::list t;
80 for(typename T::const_iterator it=x.begin; it!=x.end(); ++it)
84 static boost::python::list values(T const& x)
86 boost::python::list t;
87 for(typename T::const_iterator it=x.begin; it!=x.end(); ++it)
91 static boost::python::list items(T const& x)
93 boost::python::list t;
94 for(typename T::const_iterator it=x.begin; it!=x.end(); ++it)
95 t.append(boost::python::make_tuple(it->first,it->second));
98 static int index(T const& x, K const& k)
101 for(typename T::const_iterator it=x.begin; it!=x.end(); ++it,++i)
102 if( it->first == k ) return i;
108 #endif /*STL_CONTAINER_ADAPTER_HPP_*/