How can I extract double pairs from an std::string with Boost Spirit?
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<开发者_如何学C;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.
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
精彩评论