有效地将std :: stringstream数据解析为std :: vector <std :: vector <double>&gt; </std :: vector <double>

时间:2014-02-17 09:09:49

标签: c++ boost stl

我正在将一对双值的数据流解析为std :: vector&gt;。我使用boost,因为我觉得它更有效率。我的代码如下。

                std::stringstream tmp_stream;                
                typedef double data_type;            
                typedef ::std::vector < data_type > V_d;
                // type below describes type of the container of all data
                typedef ::std::vector < V_d > V_v_d;
                // list container 
                //typedef ::std::list < V_d > V_v_d;

                V_v_d data;

                ::data_parser::Data_parser < V_v_d > data_parser;
                data_parser ( tmp_stream, data );

我的输入文本文件格式为 {(132.181,0.683431),   (136.886,0.988517),   (137.316,0.504297),   (133.653,0.602269),   (150.86,0.236839)  } 这些对没有正确解析,我收到空对。可能是什么问题呢? 感谢

1 个答案:

答案 0 :(得分:5)

使用一点Boost Spirit,你可以使用一行:

if (tmp_stream >> std::noskipws >> 
       qi::phrase_match((+qi::double_) % qi::eol, qi::blank, data))
{

和另一行显示结果作为奖励:

    std::cout << karma::format((karma::double_ % ", ") % karma::eol, data) << "\n";
}

注意它处理inf-infnan:)

查看 Live on Coliru

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/qi_match.hpp>

namespace qi = boost::spirit::qi;
namespace karma = boost::spirit::karma;

int main()
{
    std::vector<std::vector<double>> data;

    std::stringstream tmp_stream(
            "123 45 inf -inf nan .7e-99\n"
            "42\n"
            "-1");

    if (tmp_stream >> std::noskipws >> qi::phrase_match((+qi::double_) % qi::eol, qi::blank, data))
    {
        std::cout << karma::format((karma::double_ % ", ") % karma::eol, data) << "\n";
    }
}

UPDATE 稍微适应您的输入语法,我建议将其解析为对的向量:

#include <boost/fusion/adapted/std_pair.hpp> // handle std::pair
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/qi_match.hpp>

namespace qi = boost::spirit::qi;
namespace karma = boost::spirit::karma;

int main()
{
    std::vector<std::pair<double, double>> data;

    std::stringstream tmp_stream("{ (132.181,0.683431), (136.886,0.988517), (137.316,0.504297), (133.653,0.602269), (150.86,0.236839) }");

    if (tmp_stream >> std::noskipws >> qi::phrase_match(
                   '{' 
                >> 
                     ( '(' >> qi::double_ >> "," >> qi::double_ >> ')' )
                     % ','
                >> '}',
                qi::space, data))
    {
        std::cout << karma::format(karma::delimit(" ") [karma::auto_] % karma::eol, data) << "\n";
    }
}

打印:(参见 Live On Coliru

132.181 0.683 
136.886 0.989 
137.316 0.504 
133.653 0.602 
150.86 0.237 

注意为了更快地做到这一点,请考虑不要解析表单,而是使用

  • streambuf_iterator
  • 基础字节数据,如果你已经在内存中