STLコンテナをSink/Sourceとして使う
Iostreamsでは、コンテナを入力元(Source)、出力先(Sink)として使うことができます。
Sourceとして使うには、boost::make_iterator_range関数を、
また、Sinkとして使うには、boost::iostreams::back_inserter関数を使います。
ファイルに書き出したりせず、アプリケーション内でFilter処理するだけ、ということは多いと思うので、使う機会は多いでしょう。
まずはSink
#include <iostream> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/device/back_inserter.hpp> int main(){ namespace io = boost::iostreams; std::string result; io::filtering_ostream out(io::back_inserter(result)); out << "Output to container."; out.flush(); std::cout << result << std::endl; return 0; }
Output:
Output to container.
ストリームを使って変数resultに文字列を出力することができました。
boost::iostreams::back_inserterは、Sinkモデル*1のクラスであるboost::iostreams::back_inserter_deviceのインスタンスを返します。
そしてSource
#include <iostream> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/device/back_inserter.hpp> #include <boost/iostreams/copy.hpp> int main(){ namespace io = boost::iostreams; std::string source("Input from container."); io::filtering_istream in(boost::make_iterator_range(source)); std::string dest; io::copy(in, io::back_inserter(dest)); std::cout << dest << std::endl; return 0; }
Output:
Input from container.
変数sourceから文字列を入力することができました。
boost::make_iterator_rangeは、boost::iterator_rangeクラスのインスタンスを返します。Sourceモデル*2ではないです。謎です。
バイナリデータを扱うならstd::stringではなく、std::vector