【发布时间】:2013-09-02 19:27:00
【问题描述】:
我有一个输入向量,其大小可以介于空元素和 3 个元素之间。我希望生成的字符串始终是由空格分隔的 3 个浮点数,如果向量中没有足够的元素,则使用默认值。到目前为止,我已经设法只输出了向量的内容:
#include <iostream>
#include <iterator>
#include <vector>
#include "boost/spirit/include/karma.hpp"
namespace karma = boost::spirit::karma;
namespace phx = boost::phoenix;
typedef std::back_insert_iterator<std::string> BackInsertIt;
int main( int argc, char* argv[] )
{
std::vector<float> input;
input.push_back(1.0f);
input.push_back(2.0f);
struct TestGram
: karma::grammar<BackInsertIt, std::vector<float>(), karma::space_type>
{
TestGram() : TestGram::base_type(output)
{
using namespace karma;
floatRule = double_;
output = repeat(3)[ floatRule ];
}
karma::rule<BackInsertIt, std::vector<float>(), karma::space_type> output;
karma::rule<BackInsertIt, float(), karma::space_type> floatRule;
} testGram;
std::string output;
BackInsertIt sink(output);
karma::generate_delimited( sink, testGram, karma::space, input );
std::cout << "Generated: " << output << std::endl;
std::cout << "Press enter to exit" << std::endl;
std::cin.get();
return 0;
}
我尝试将浮动规则修改为:floatRule = double_ | lit(0.0f),但这只会给我带来编译错误。我尝试过的许多其他类似的东西也是如此。
我真的不知道如何让它工作。一些帮助会很棒:)
编辑:只是为了说清楚。如果我有一个包含 2 个元素的向量:1.0 和 2.0,我想生成一个如下所示的字符串:"1.0 2.0 0.0"(最后一个值应该是默认值)。
【问题讨论】:
标签: c++ boost-spirit boost-spirit-karma