gpt4 book ai didi

c++ - 即时创建和写入 vector

转载 作者:行者123 更新时间:2023-11-30 04:01:19 24 4
gpt4 key购买 nike

我想在一个精神规则中创建 vector 并为其附加值(如果有的话)。是否可以?我尝试了类似下面的方法,但没有成功。请阅读代码注释以获取详细信息。谢谢。

typedef std::vector<double> number_array;
typedef std::vector<std::string> string_array;

typedef boost::variant<number_array, string_array> node

template<typename Iterator>
struct parser
: qi::grammar<Iterator, node(), ascii::space_type> {

parser(parser_impl* p)
: parser::base_type(expr_, ""),
error_handler(ErrorHandler(p)) {

// Here I want to create vector on the fly
// and append values to newly created vector.
// but this doesn't compile, specifically phoenix::push_back(...)
number_array_ = qi::lit('n[')[qi::_val = construct<number_array>()] >>
-(qi::double_ % ',')[phoenix::push_back(phoenix::ref(qi::_val), qi::_1)] >> ']';

// this doesn't compile too
string_array_ = qi::lit('s[')[qi::_val = construct<string_array>()] >>
-(quoted_string % ',')[phoenix::push_back(phoenix::ref(qi::_val), qi::_1)] >> ']';

quoted_string %= "'" > qi::lexeme[*(qi::char_ - "'")] > "'";

expr_ = number_array_[qi::_val = qi::_1] | string_array_[[qi::_val = qi::_1]];
}
qi::rule<Iterator, number_array(), ascii::space_type> number_array_;
qi::rule<Iterator, string_array(), ascii::space_type> string_array_;
qi::rule<Iterator, std::string(), ascii::space_type> quoted_string;
qi::rule<Iterator, node(), ascii::space_type> expr_;
};

最佳答案

这里最重要的一点是,我认为您可以不使用所有语义操作。

它们只执行默认属性规则已经执行的操作(_val = _1 用于标量属性,insert(_val, end(_val), _1) 用于容器属性,基本上)。

这意味着您可以将整个 shebang 写成

    number_array_ = "n[" >> -(qi::double_ % ',')   >> ']';
string_array_ = "s[" >> -(quoted_string % ',') >> ']';

quoted_string = "'" > qi::lexeme[*(qi::char_ - "'")] > "'";

expr_ = number_array_ | string_array_;

这会奏效。请注意,我修复了多字节文字 'n[''s[n'

另见 Boost Spirit: "Semantic actions are evil"?

关于c++ - 即时创建和写入 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25849086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com