views:

57

answers:

1

I want to parse a string with a sequence of double pairs into an std::map with Boost Spirit.

I adapted the example from http://svn.boost.org/svn/boost/trunk/libs/spirit/example/qi/key_value_sequence.cpp but I have a problem with difining a proper qi::rule for key and value:

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

I can't use double() for the the key and value rules and an std::string can't be constructed from an double.

A: 

I am not sure why you can't use double() key and value when your output requirement is

 map<double, double>.

As i understand the problem the below code should solve it.

 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()'
 };

The above code parses the input of double sequence 1323.323,32323.232,3232.23,32222.23 into

map[1323.323] = 32323.232

map[3232.23] = 32222.23

aeh
Yes, this works. Thanks!
Jens