gpt4 book ai didi

c++ - 将两个整数的序列匹配到 `std::pair`

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:42:48 24 4
gpt4 key购买 nike

我正在尝试使用 Boost.Sprit x3将两个整数的序列匹配到 std::pair<int, int> .根据文档判断,应编译以下代码:


#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<int, int> result;int result;然后打印 result , 我得到 1作为我的输出。

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

最佳答案

实际上,@T.C.包括 <boost/fusion/adapted/std_pair.hpp> 的评论仅足以使编译器静音,而不能正确解析您的字符串。我还必须更改 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 符号转储到您的代码中。

关于c++ - 将两个整数的序列匹配到 `std::pair<int, int>`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38816282/

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