Skip to content

Instantly share code, notes, and snippets.

@QuantTraderEd
Last active December 31, 2019 14:51
Show Gist options
  • Save QuantTraderEd/4d1a79418461aabcd438 to your computer and use it in GitHub Desktop.
Save QuantTraderEd/4d1a79418461aabcd438 to your computer and use it in GitHub Desktop.
boost python helper
#include <boost/python.hpp>
#include <boost/python/stl_iterator.hpp>
#include <vector>
#include <unordered_map>
namespace lymc {
namespace python = boost::python;
template<class T1, class T2>
struct tuple_to_pair:
public std::unary_function<python::tuple, std::pair<T1, T2> >
{
public:
typedef tuple argument_type;
typedef std::pair<T1, T2> result_type;
result_type operator()(const argument_type& arg);
};
template<class Container>
struct map_insert_iterator:
public std::iterator<std::output_iterator_tag, typename Container::value_type>
{
public:
typedef Container container_type;
explicit map_insert_iterator(Container& x):
container(x) {}
map_insert_iterator<Container>& operator*() { return *this; }
map_insert_iterator<Container>& operator++() { return *this; }
map_insert_iterator<Container>& operator=(typename Container::const_reference value) {
container.insert(value);
return *this;
}
protected:
Container& container;
};
template<class Container>
inline map_insert_iterator<Container> map_inserter(Container& container) {
return map_insert_iterator<Container>(container);
}
template<class T1, class T2>
inline std::unordered_map<T1, T2> dict_to_map(const python::dict& d) {
std::unordered_map<T1, T2> result;
python::stl_input_iterator<tuple> begin(d.iteritems()), end;
std::transform(begin, end, map_inserter(result),
boost::bind(tuple_to_pair<T1, T2>(), _1));
return result;
}
template<typename T>
inline
std::vector< T > list_to_std_vector( const python::list& iterable )
{
return std::vector< T >( python::stl_input_iterator< T >( iterable ),
python::stl_input_iterator< T >( ) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment