如何找到n次出现的带有boost spirit的表情?

How to find n occurences of an expression with boost spirit?

我已将此语法传递给 phrase_parse()

double_[push_back(phoenix::ref(v), _1)] >> *(*blank >> double_[push_back(phoenix::ref(v), _1)])

*(*blank开头的第二个表达式,找出0次或多次出现的 'double'。在我的例子中,我想确保它恰好匹配 6 次。有没有可能在精神振奋的情况下做到这一点?

使用 repeat directive. There's no need to use semantic actions either when parsing a list of numbers, all you need is the % 运算符。在这种情况下,由于您的数字由空格分隔,因此您也不需要使用它,传递给 phrase_parse 的船长就可以了。

auto result = qi::phrase_parse(first, last,
                               qi::repeat(6)[qi::double_],
                               qi::space,
                               v);

Live demo

完整示例:

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

#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;

void parse(std::string const& s)
{
    auto first = s.cbegin(), last = s.cend();
    std::vector<double> v;

    auto result = qi::phrase_parse(first, last,
                                   qi::repeat(6)[qi::double_],
                                   qi::space,
                                   v);
    if(result) {
        if(first == last) {
            std::cout << "Success (complete)  : ";
        } else {
            std::cout << "Success (incomplete): ";
        }
        for(auto d : v) std::cout << d << ' ';
        std::cout << " Remaining: " << std::string{first, last} << '\n';

    } else {
        std::cout << "Failed\n";
    }
}

int main()
{
    parse("10 20   30 40 50       60      ");
    parse("10 20   30 40 50       60 70 80");
    parse("10 20   30 40");
}

输出:

Success (complete)  : 10 20 30 40 50 60  Remaining: 
Success (incomplete): 10 20 30 40 50 60  Remaining: 70 80
Failed