C++ Boost 精神,将二维数组(以及更多)解析为结构

标签 c++ arrays boost-spirit-qi

我正在尝试修改以下示例:http://www.boost.org/doc/libs/1_57_0/libs/spirit/example/qi/employee.cpp

我想在 employee 结构中添加一个 2D vector ,例如:

struct employee
{
    int age;
    std::string surname;
    std::string forename;
    double salary;
    std::vector<std::vector<int> > work_hours;
};

解析类似的东西

employee{42, "Foo", "Bar", 0
1 2 3
4 5 6 7 8
}

所以 work_hours = {{1,2,3},{4,5,6,7,8}}。 (我真的需要一个二维数组,因为子 vector 的长度可以变化)。

我修改了 BOOST_ADAPT_STRUCT,并将解析规则更改为:

start %=
            lit("employee")
            >> '{'
            >>  int_ >> ','
            >>  quoted_string >> ','
            >>  quoted_string >> ','
            >>  double_
            >>  +(qi::int_) % qi::eol
            >>  '}'
            ;

不幸的是,此规则使精神返回 work_hours = {{1,2,3,4,5,6,7,8}},而不是:{{1,2,3},{4,5,6 ,7,8}}

有人有解决方法吗?

提前致谢

最佳答案

qi::eol 被 skip 解析器匹配,所以你必须在 lexeme 指令中进行列表解析。例如:

        start %=
            lit("employee")
            >> '{'
            >>  int_ >> ','
            >>  quoted_string >> ','
            >>  quoted_string >> ','
            >>  double_
            >>  *lexeme[int_ % ' '] // <-- here
            >>  '}'
            ;

lexeme[int_ % ' '] 不使用跳过解析器,因此它将匹配由一个空格分隔的整数。如果您希望整数由多个空格分隔(出于缩进目的等),并且根据您希望处理制表符和其他非换行空格的方式,您可以使用更复杂的分隔符。可能最接近您的原始代码是

            >>  *lexeme[int_ % +(ascii::space - '\n')]

不过,究竟什么是最好的方法是您必须自己回答的问题。

关于C++ Boost 精神,将二维数组(以及更多)解析为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28252821/

相关文章:

html - Representative.replace()在数组列表Grails 2.3.8上不起作用

javascript - Angularjs watch 无法处理对象内部的数组

c++ - qi::rule 以继承属性作为继承属性

c++ - Boost::spirit::qi 解析器不消耗整个字符串

c++ - Boost::Python 中的运算符=

c++ - ( vector ?)析构函数中的读取访问冲突

c++ - 为什么使用预编译 header 会导致构建变慢?

c++ - typeinfo 和dynamic_cast 外部未解析

c - 从数组中添加/删除元素

c++ - boost spirit 解析标识符