ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – 用容器解析结构

2019-07-24 19:06:54  阅读:209  来源: 互联网

标签:boost-spirit-x3 c c14 boost boost-spirit


如何使用boost.spirit x3解析为如下结构:

struct person{
    std::string name;
    std::vector<std::string> friends;
}

来自boost.spirit v2我会使用语法,但由于X3不支持语法,我不知道如何干净.

编辑:如果有人可以帮我编写一个解析字符串列表的解析器并返回第一个字符串的人是名称而字符串的res在朋友矢量中,那将是很好的.

解决方法:

使用x3解析比使用v2简单得多,因此移动时不会有太多麻烦.语法消失是件好事!

以下是如何解析字符串向量:

//#define BOOST_SPIRIT_X3_DEBUG

#include <fstream>
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>

#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/ast/variant.hpp>

namespace x3 = boost::spirit::x3;

struct person
{
    std::string name;
    std::vector<std::string> friends;
};

BOOST_FUSION_ADAPT_STRUCT(
    person,
    (std::string, name)
    (std::vector<std::string>, friends)
);

auto const name = x3::rule<struct name_class, std::string> { "name" }
                = x3::raw[x3::lexeme[x3::alpha >> *x3::alnum]];

auto const root = x3::rule<struct person_class, person> { "person" }
                = name >> *name;

int main(int, char**)
{
    std::string const input = "bob john ellie";
    auto it = input.begin();
    auto end = input.end();

    person p;
    if (phrase_parse(it, end, root >> x3::eoi, x3::space, p))
    {
        std::cout << "parse succeeded" << std::endl;
        std::cout << p.name << " has " << p.friends.size() << " friends." << std::endl;
    }
    else
    {
        std::cout << "parse failed" << std::endl;
        if (it != end)
            std::cout << "remaining: " << std::string(it, end) << std::endl;
    }

    return 0;
}

如您所见,on Coliru,输出为:

parse succeeded
bob has 2 friends.

标签:boost-spirit-x3,c,c14,boost,boost-spirit
来源: https://codeday.me/bug/20190724/1525144.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有