本文介绍了在一个std ::地图&LT店价值;的std ::字符串,性病::字符串>使用boost ::精神::齐:: phrase_parse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在试图让使用的boost ::精神::齐:: phrase_parse 做了一些工作,但我不能靠自己想出解决办法。

I'm currently trying to get some work done using boost::spirit::qi::phrase_parse but I'm not able to figure this out by myself.

值得一提:我完全新的提高,因此提高::精神

Worth mentioning: I'm totally new to boost and so to boost::spirit.

我得到表单的输入{A [BC] - > F [DE],C - > E,B-> Z}

我想这种类型的输入解析为的std ::地图<的std ::字符串,性病::字符串> 。关键应持有每的std :: string的 - >中和每一个值的std :: string的的 - >中直到发生。

I'd like to parse this type of input into a std::map<std::string, std::string>. The key should hold every std::string before the "->" and the value every std::string after the "->" until the ',' occurs.

此外,'[']不宜存放。

所以性病的内容::地图应该是这样解析成功后:

So the content of the std::map should be something like this after the parsing succeeded:

     {
       ("A", "F"),
       ("A", "D E"),
       ("B C", "F"),
       ("B C", "D E"),
       ("C", "E"),
       ("B", "Z")
     }

我的第一种方法是将所有键/值存储在一个的std ::矢量&lt;标准::字符串方式&gt;

    #include <boost/spirit/include/qi.hpp>

    #include <iostream>
    #include <string>
    #include <vector>

    int main()
    {
        using boost::spirit::qi::phrase_parse;
        using boost::spirit::qi::char_;
        using boost::spirit::qi::lexeme;

        std::string input = "{A [B C] -> F [D E], C    ->E,B->Z}";
        std::string::const_iterator beg = input.begin(), end = input.end();

        std::vector<std::string> sdvec;

        bool r = phrase_parse(  beg, 
                                end,
                                '{' >> (+(+char_("a-zA-Z0-9") | lexeme[('[' >> +char_("a-zA-Z0-9 ") >> ']')]) >> '-' >> '>' >> +(+char_("a-zA-Z0-9") | lexeme[('[' >> +char_("a-zA-Z0-9 ") >> ']')])) % ',' >> '}',
                                boost::spirit::ascii::space,
                                sdvec
                           );

        if(beg != end) {
            std::cout << "Parsing failed!" << std::endl;
        } else {
            std::cout << "Parsing succeeded!" << std::endl;    
        }

        for(int i=0; i<sdvec.size(); i++) {
            std::cout << i << ": " << sdvec[i] << std::endl;
        }

        return 0;
    }

执行这个我越来越发现每个的std ::字符串的std ::向量的条目

    Parsing 2 succeeded!
    0: A
    1: B C
    2: F
    3: D E
    4: C
    5: E
    6: B
    7: Z

但我不知道如何将这些值解析为的std ::地图&LT;的std ::字符串,性病::字符串&GT; 使用的boost ::精神::齐:: phrase_parse 作为简单地更换一些抛出编译错误。

But I've no idea how to parse these values into a std::map<std::string, std::string> using boost::spirit::qi::phrase_parse as simply replacing throws some compiling errors.

编辑:

其实我发现的东西是相当我需要什么:http://boost-spirit.com/home/articles/qi-example/parsing-a-list-of-key-value-pairs-using-spirit-qi/

Actually I found something that's quite what I need: http://boost-spirit.com/home/articles/qi-example/parsing-a-list-of-key-value-pairs-using-spirit-qi/

我根据我的问题通过本文的code:

I adopted the code of this article according to my problem:

    #include <boost/spirit/include/qi.hpp>
    #include <boost/fusion/include/std_pair.hpp>

    #include <iostream>
    #include <string>
    #include <vector>
    #include <map>

    namespace qi = boost::spirit::qi;

    template <typename Iterator>
    struct keys_and_values
      : qi::grammar<Iterator, std::map<std::string, std::string>()>
    {
        keys_and_values()
          : keys_and_values::base_type(query)
        {
            query =  '{' >> *qi::lit(' ') >> pair >> *(qi::lit(',') >> *qi::lit(' ') >> pair) >> *qi::lit(' ') >> '}';
            pair  =  key >> -(*qi::lit(' ') >> "->" >> *qi::lit(' ') >> value);
            key   =  +qi::char_("a-zA-Z0-9") | qi::lexeme[('[' >> +qi::char_("a-zA-Z0-9 ") >> ']')];
            value = +qi::char_("a-zA-Z0-9") | qi::lexeme[('[' >> +qi::char_("a-zA-Z0-9 ") >> ']')];
        }
        qi::rule<Iterator, std::map<std::string, std::string>()> query;
        qi::rule<Iterator, std::pair<std::string, std::string>()> pair;
        qi::rule<Iterator, std::string()> key, value;
    };

    int main()
    {
        std::string input = "{AB -> CD, E -> F, G -> HI, [J K L] -> [M N O]                   }";

        std::string::iterator begin = input.begin();
        std::string::iterator end = input.end();

        keys_and_values<std::string::iterator> p;    // create instance of parser
        std::map<std::string, std::string> m;        // map to receive results
        bool result = qi::phrase_parse(begin, end, p, boost::spirit::ascii::space, m);   // returns true if successful

        if(begin != end) {
            std::cout << "Parsing failed!" << std::endl;
        } else {
            std::cout << "Parsing succeeded!" << std::endl;    
        }

        std::cout << m["AB"] << "\t" << m["E"] << "\t" << m["G"] << "\t" << m["J K L"] << std::endl;

        return 0;
    }

这样做的结果是多还是少了什么,我需要:

The result of this is more or less what I need:

Parsing succeeded!
CD  F   HI  M N O

我来解决最后的问题就是像 A [B C]的情况 - &GT; F [D E]

什么办法让那些四分开键 - 值对(A,F),(A,DE),(BC,F) (BC,DE)进入我的的std ::地图&LT;的std ::字符串,性病::字符串&GT;米

Any way to get those as four separated key-value pairs ("A", "F"), ("A", "D E"), ("B C", "F"), ("B C", "D E") into my std::map<std::string, std::string> m?

或者,也许更容易把它解析为的std ::地图&LT;的std ::矢量&lt;标准::字符串&gt;中的std ::矢量&lt;标准::字符串&GT; &GT; ,其中每个的std ::矢量&lt;标准::字符串&GT; 持有的所有键/值

Or maybe it's easier to parse it into a std::map<std::vector<std::string>, std::vector<std::string> > where each std::vector<std::string> holds all keys/values?

例如:

in: "{A [B C] -> F [D E], C ->E,B->Z}"
out: { ({"A", "B C"}, {"F", "D E"}), ({"C"}, {"E"}), ({"B"}, {"Z"}) }

感谢您的帮助!

推荐答案

我觉得你很接近你的目标,所以我会跳过组合的一部分:-)
解析器会做它应该做的事情......检查语法和来标记数据然后将其传递键,值和输出图(多重映射)参数成凤功能插入在那里你可以插入任何在您需要的地图(多重映射)

I think you are quite close to your goal so I will skip the combinatorial part :-)The parser will do the things it is supposed to do ... to check the syntax and to tokenize data then it passes keys, values and output map ( multimap ) arguments into phoenix function inserter where you can insert whatever you need in your map ( multimap )

#if __cplusplus >= 201103L
#define BOOST_RESULT_OF_USE_DECLTYPE
#endif
#define BOOST_SPIRIT_USE_PHOENIX_V3
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <iomanip>
#include <vector>
#include <map>

namespace qi = boost::spirit::qi;
namespace ascii=boost::spirit::ascii;

typedef std::map< std::string,std::string > TMap;
//typedef std::multimap< std::string,std::string > TMap;

struct SMapInsert
{
    template <typename Arg1,typename Arg2,typename Arg3>
    struct result
    {
        typedef void type;
    };

    template <typename Arg1,typename Arg2,typename Arg3>
    void operator()( Arg1&out, Arg2&keys, Arg3&vals ) const
    {
        std::cout << "Keys:" << std::endl;
        for( const auto &key : keys )
            std::cout << std::left << "`" << key << "`" << std::endl;
        std::cout << "Vals:" << std::endl;
        for( const auto &val : vals )
            std::cout << std::left << "`" << val << "`" << std::endl;
        // your map here...
        // out.insert
    }
};

boost::phoenix::function< SMapInsert > inserter;

int main()
{
    std::string input = "{A [B C] -> F [D E], C ->E,B->Z}";
    TMap data;

    std::string::const_iterator iter = input.begin();
    std::string::const_iterator last = input.end();

    qi::rule< std::string::const_iterator,std::string() > token=+qi::alnum;
    qi::rule< std::string::const_iterator,ascii::space_type,std::vector< std::string >() > 
        keyOrvalue = +( token  | ( '[' >> qi::lexeme[ +qi::char_("a-zA-Z0-9 ") ] >> ']' ) );
    qi::rule< std::string::const_iterator,ascii::space_type, TMap() > 
        root = '{' >> ( ( keyOrvalue >> "->" >> keyOrvalue )[ inserter( qi::_val, qi::_1, qi::_2 ) ] ) % ',' >> '}';
    std::cout << "input: `" << input << "`" << std::endl;
    if( qi::phrase_parse( iter, last, root, ascii::space, data ) && iter==last )
    {
        for( const auto &keyValue : data )
            std::cout << std::left << std::setw(10) << keyValue.first << std::setw(10) << keyValue.second << std::endl;
    } 
    else
        std::cout << "parsing failed:" << std::string( iter,last ) << std::endl;        

    return 0;
}

这篇关于在一个std ::地图&LT店价值;的std ::字符串,性病::字符串&GT;使用boost ::精神::齐:: phrase_parse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 20:52