1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Boost.Qiのqi::ruleについて少し調べた(1)

Last updated at Posted at 2020-09-25

qi::ruleというものがあるが、これも初心者には分かりにくい。

英語で見てみる。。。
https://theboostcpplibraries.com/boost.spirit-rules

boost::spirit::ascii::digit can be both a parser and a rule. Typically, rules refer to more complicated expressions like qi::int_ % ','.

つまり、整数, 整数, というcsv的な表現はかさばるので、qi::ruleを使って名前をつけてしまうと吉ということではないだろうか。

プログラムを見てみる。。。

3,4,5といった文字列のコンマを、セミコロンに変換したいとする。

 1#include <boost/spirit/include/qi.hpp>
 2#include <string>
 3#include <vector>
 4#include <iterator>
 5#include <algorithm>
 6#include <iostream>
 7
 8using namespace boost::spirit;
 9
10int main()
11{
12  std::string s;
13  std::getline(std::cin, s);
14  auto it = s.begin();
15  qi::rule<std::string::iterator, std::vector<int>(),
16           ascii::space_type> values = qi::int_ % ',';
17  std::vector<int> integer_vector;
18  if (qi::phrase_parse(it, s.end(), values, ascii::space, integer_vector))
19    {
20      std::cout << "parse OK" << std::endl;
21      std::ostream_iterator<int> out{std::cout, ";"};
22      std::copy(integer_vector.begin(), integer_vector.end(), out);
23    }
24  else
25    std::cout << "parse fail" << std::endl;

+c++ 15 qi::rule<std::string::iterator, std::vector<int>(), 16 ascii::space_type> values = qi::int_ % ','; +

であるが、これは、qi::int_ % ','というパース規約にvaluesをいう名前を付けている。
このvaluesというruleを、18行目で使っている。

+c++ 18 if (qi::phrase_parse(it, s.end(), values, ascii::space, integer_vector)) +

実行してみる。。。


$ ./a.out 
2,3,4
parse OK
2;3;4;
$ ./a.out 
string
parse fail
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?