代码之家  ›  专栏  ›  技术社区  ›  Jens Luedicke

如何使用Boost Spirit从std::字符串中提取双对?

  •  0
  • Jens Luedicke  · 技术社区  · 14 年前

    我想把一个包含双对序列的字符串解析成一个std::map 精神振奋。

    http://svn.boost.org/svn/boost/trunk/libs/spirit/example/qi/key_value_sequence.cpp 但是我在为键和值定义一个正确的qi::规则时遇到了一个问题:

    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;
    };
    

    1 回复  |  直到 14 年前
        1
  •  0
  •   aeh    14 年前

     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.32323.23232.2332222.23的输入解析为

    地图[1323.323]=32323.232

    地图[3232.23]=32222.23