来自 std::vector <double>的未格式化流输入

unformatted stream input from std::vector<double>

本文关键字:格式化 输入 gt std lt 来自 double vector      更新时间:2023-10-16

我正在使用boost::iostream lib来包装到gnuplot的posix管道。为了将二进制内联数据发送到gnuplot,我目前正在做类似于的事情

std::vector<double> d = test_data();
Gnuplot plt; //custom gnuplot class derived from boost::iostream::stream
plt << "plot '-' binary format='%double' notitlen"
plt.write( (char*)( &c.front() ), sizeof(double)*c.size() ); // send binary data

它是有效的,但我想去掉.write,并使用迭代器接口来允许例如std::list作为源。我知道std::ostreambuf_editor允许无格式的输入,但简单地使用std::copy显然不起作用。

这里有一个简单的包装器模板来写出范围:

#include <memory>
#include <iterator>
template <typename FwdIter>
write_range(Gnuplot & gp, FwdIter it, FwdIter end)
{
    typedef typename std::iterator_traits<FwdIter>::value_type type;
    for ( ; it != end; ++it)
    {
        gp.write(reinterpret_cast<char const *>(std::addressof(*it)), sizeof(type));
    }
}

用法:write_range(gp, mylist.begin(), mylist.end());