栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Boost :: Python-可以自动从dict-> std :: map转换吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Boost :: Python-可以自动从dict-> std :: map转换吗?

我认为,有两种方法比编写自己的转换器更容易实现。您可以使用boost ::
python的map_indexing_suite为您进行转换,也可以在python中使用关键字参数。我个人更喜欢关键字参数,因为这是更“
Pythonic”的方式。

这是您的课程(我为地图添加了typedef):

typedef std::map<std::string, double> MyMap;class myClass {public:    // Constructors - set a-f to default values.    void SetParameters(MyMap &);private:    double a, b, c, d, e, f;};

使用map_indexing_suite的示例:

#include <boost/python/suite/indexing/map_indexing_suite.hpp>using boost::python;BOOST_PYTHON_MODULE(mymodule){    class_<std::map<std::string, double> >("MyMap")        .def(map_indexing_suite<std::map<std::wstring, double> >() );    class_<myClass>("myClass")        .def("SetParameters", &myClass::SetParameters);}

使用关键字参数的示例。这需要使用raw_function包装器:

using namespace boost::python;object SetParameters(tuple args, dict kwargs){    myClass& self = extract<myClass&>(args[0]);    list keys = kwargs.keys();    MyMap outMap;    for(int i = 0; i < len(keys); ++i) {        object curArg = kwargs[keys[i]];        if(curArg) { outMap[extract<std::string>(keys[i])] = extract<double>(kwargs[keys[i]]);        }        }    self.SetParameters(outMap);    return object();}BOOST_PYTHON_MODULE(mymodule){    class_<myClass>("myClass")        .def("SetParameters", raw_function(&SetParameters, 1));}

这使您可以在Python中编写如下内容:

A.SetParameters(a = 2.2, d = 4.3, b = 9.3)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/668287.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号