【问题标题】:Matching a sequence of two integers into an `std::pair<int, int>`将两个整数的序列匹配为 `std::pair<int, int>`
【发布时间】:2016-08-07 16:35:53
【问题描述】:

我正在尝试使用Boost.Sprit x3 将两个整数的序列匹配为std::pair&lt;int, int&gt;。从文档来看,以下代码应该可以编译:


#include <string>
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/home/x3.hpp>

int main()
{
    using namespace boost::spirit::x3;

    std::string input("1 2");
    std::pair<int, int> result;
    parse(input.begin(), input.end(), int_ >> int_, result);
}

melpon.org link


但是,它只匹配第一个整数。如果我将std::pair&lt;int, int&gt; result; 更改为int result; 然后打印result,我会得到1 作为我的输出。

为什么会这样? int_ &gt;&gt; int_ 不是定义匹配(并设置为属性)两个整数的解析器的正确方法吗?

【问题讨论】:

  • 看来你需要包含适应std::pair的相关Boost.Fusion标头。
  • @T.C.:是的,这解决了问题。谢谢!发表您的评论作为答案,我会接受。

标签: c++ c++14 boost-fusion boost-spirit-x3


【解决方案1】:

实际上,@T.C.包含&lt;boost/fusion/adapted/std_pair.hpp&gt; 的评论仅足以使编译器静音,而不能正确解析您的字符串。我还必须将x3::parse() 更改为跳过空格的x3::phrase_parse()

#include <iostream>
#include <string>
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/adapted/std_pair.hpp>

int main()
{
    namespace x3 = boost::spirit::x3;

    std::string input("1 2");
    std::pair<int, int> result;
    auto ok = x3::phrase_parse(input.begin(), input.end(), x3::int_ >> x3::int_, x3::space, result);
    std::cout << std::boolalpha << ok << ": ";
    std::cout << result.first << ", " << result.second;
}

Live Example

请注意,我还将您的 using namespace boost::spirit::x3 替换为命名空间别名 x3。这将保持可读性,但会防止将大量 Boost.Spirit 符号转储到您的代码中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 2011-10-29
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    相关资源
    最近更新 更多