我想解析一个布尔表达式(在C++中).输入表格:
a and b xor (c and d or a and b);
Run Code Online (Sandbox Code Playgroud)
我只想将这个表达式解析为树,知道优先级规则(不是,和,xor,或).所以上面的表达式应该类似于:
(a and b) xor ((c and d) or (a and b));
Run Code Online (Sandbox Code Playgroud)
到解析器.
树将是以下形式:
a
and
b
or
c
and
d
xor
a
and
b
Run Code Online (Sandbox Code Playgroud)
输入将通过命令行或以字符串的形式.我只需要解析器.
有没有可以帮助我做到这一点的消息来源?
我的boost :: spirit解析器还有另外一个问题.
template<typename Iterator>
struct expression: qi::grammar<Iterator, ast::expression(), ascii::space_type> {
expression() :
expression::base_type(expr) {
number %= lexeme[double_];
varname %= lexeme[alpha >> *(alnum | '_')];
binop = (expr >> '+' >> expr)[_val = construct<ast::binary_op<ast::add>>(_1,_2)]
| (expr >> '-' >> expr)[_val = construct<ast::binary_op<ast::sub>>(_1,_2)]
| (expr >> '*' >> expr)[_val = construct<ast::binary_op<ast::mul>>(_1,_2)]
| (expr >> '/' >> expr)[_val = construct<ast::binary_op<ast::div>>(_1,_2)] ;
expr %= number | varname | binop;
}
qi::rule<Iterator, ast::expression(), ascii::space_type> expr;
qi::rule<Iterator, ast::expression(), ascii::space_type> binop;
qi::rule<Iterator, std::string(), ascii::space_type> varname;
qi::rule<Iterator, …Run Code Online (Sandbox Code Playgroud) 我想定义一个带有2个参数的函数
double func(double t, double x);
Run Code Online (Sandbox Code Playgroud)
从外部文本文件中读取实际实现的位置.
例如,在文本文件中指定
function = x*t;
Run Code Online (Sandbox Code Playgroud)
功能应该实现的乘法x和t,以便它可以在稍后阶段被调用.我正在尝试使用boost :: spirit来解析函数.但我不知道如何实现它.
下面,我创建了一个实现乘法的简单函数.我将它绑定到boost函数,我可以使用它.我还创建了一个简单的语法,它解析了两个双精度数之间的乘法.
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include "boost/function.hpp"
#include "boost/bind.hpp"
#include <boost/spirit/include/qi_symbols.hpp>
#include <iostream>
#include <string>
namespace qi = boost::spirit::qi;
namespace ascii=boost::spirit::ascii;
using boost::spirit::ascii::space;
using boost::spirit::qi::symbols;
template< typename Iterator >
struct MyGrammar : public virtual qi::grammar< Iterator, ascii::space_type >
{
MyGrammar() : MyGrammar::base_type(expression)
{
using qi::double_;
//The expression should take x and t as symbolic expressions
expression = (double_ >> '*' …Run Code Online (Sandbox Code Playgroud)