【问题标题】:How can I extract double pairs from an std::string with Boost Spirit?如何使用 Boost Spirit 从 std::string 中提取双对?
【发布时间】:2011-04-09 14:57:08
【问题描述】:

我想将带有双对序列的字符串解析为 std::map 使用 Boost Spirit。

我改编了这个例子 http://svn.boost.org/svn/boost/trunk/libs/spirit/example/qi/key_value_sequence.cpp 但我在为键和值定义适当的 qi::rule 时遇到问题:

template <typename Iterator>
struct keys_and_values : qi::grammar<Iterator, std::map<double, double> >
{
    keys_and_values()
      : keys_and_values::base_type(query)
    {
        query =  pair >> *(qi::lit(',') >> pair);
        pair  =  key >> value;

        key   =  qi::double_;
        value = +qi::double_;
    }

    qi::rule<Iterator, std::map<double, double>()>  query;
    qi::rule<Iterator, std::pair<double, double>()> pair;
    qi::rule<Iterator, std::string()>               key, value;
};

我不能将 double() 用于键和值规则,而 std::string 不能 由双精度构成。

【问题讨论】:

    标签: c++ boost boost-spirit


    【解决方案1】:

    当你的输出要求是

     map<double, double>.
    

    据我了解,下面的代码应该可以解决它。

     template <typename Iterator>
     struct keys_and_values : qi::grammar<Iterator, std::map<double, double>() >
     {
         keys_and_values()
           : keys_and_values::base_type(query)
         {
             query =  pair >> *(qi::lit(',') >> pair);
             pair  =  key >> -(',' >> value);     // a pair is also separated by comma i guess
    
             key   =  qi::double_;
            value = qi::double_;    // note the '+' is not required here
         }
    
         qi::rule<Iterator, std::map<double, double>()>  query;
         qi::rule<Iterator, std::pair<double, double>()> pair;
         qi::rule<Iterator, double()>               key, value;    // 'string()' changed to 'double()'
     };
    

    以上代码将双序列1323.323,32323.232,3232.23,32222.23的输入解析成

    地图[1323.323] = 32323.232

    地图[3232.23] = 32222.23

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多