【问题标题】:Boost property_tree - working with simple arrays or containersBoost property_tree - 使用简单的数组或容器
【发布时间】:2011-02-13 18:39:20
【问题描述】:

我正在使用 boost property_tree 加载一个 ini 文件。我的 ini 文件主要包含“简单”类型(即字符串、整数、双精度等),但我确实有一些表示数组的值。

[Example]
thestring = string
theint = 10
theintarray = 1,2,3,4,5
thestringarray = cat, dog, bird

我无法弄清楚如何提升以编程方式将theintarraythestringarray 加载到vectorlist 等容器对象中。我是不是注定只能以字符串的形式读入并自己解析出来?

谢谢!

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    是的,你注定要自己解析。但这相对容易:

    template<typename T>
    std::vector<T> to_array(const std::string& s)
    {
      std::vector<T> result;
      std::stringstream ss(s);
      std::string item;
      while(std::getline(ss, item, ',')) result.push_back(boost::lexical_cast<T>(item));
      return result;
    }
    

    可以使用的:

    std::vector<std::string> foo = 
        to_array<std::string>(pt.get<std::string>("thestringarray"));
    
    std::vector<int> bar =
        to_array<int>(pt.get<std::string>("theintarray"));
    

    【讨论】:

    • 我是 boost 新手……但 split 仅适用于字符串吗?所以我不能用这个函数来填充vector&lt;int&gt;?
    • @Polybox:实际上,当我问这个问题减去模板和 lexical_cast 时,我得到了完全相同的代码......但是现在我进行了修改,我得到了一个 no matching function for call 编译器错误。 .c++ 的乐趣... :)
    • @TReddy:找不到哪个函数?我已经测试了我的模板,它实际上运行良好。
    • @Polybox:你什么都没做......我的模板实际上是在一个抽象类中,所以我不得不根据这个讨论将 impl 添加到头文件中:stackoverflow.com/questions/1111440/…
    猜你喜欢
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 2015-01-12
    • 2019-02-11
    • 2018-10-18
    • 2013-09-24
    相关资源
    最近更新 更多