4

キーと値のペアのファイルを std::map に読み込みたい Visual Studio 2008 C++03 プロジェクトがあります。istreambuf_pair_iteratorそのために、以下のように作成しました。

typedef std::map< std::string, std::string > Properties;

class istreambuf_pair_iterator : 
    public boost::iterator_adaptor< istreambuf_pair_iterator, 
                                    std::pair< std::string, std::string >*,
                                    boost::use_default, 
                                    boost::forward_traversal_tag >
{
public:
    istreambuf_pair_iterator() : sb_( 0 ) { };
    explicit istreambuf_pair_iterator( std::istream& is ) : sb_( is.rdbuf() ) { };

    private:
    void increment()
    {
        std::string line;
        std::istream is( sb_ );
        std::getline( is, line );

        // TODO: parse the key=value to a std::pair 
        // where do I store the pair???
    };

    friend class boost::iterator_core_access;
    std::streambuf* sb_;
};

Properties ReadProperties( const char* file )
{
    std::ifstream f( file );
    Properties p;
    std::copy( istreambuf_pair_iterator( f ),
               istreambuf_pair_iterator(),
               std::inserter( p, p.end() ) );
    return p;
}

ファイルから読み取った文字列から作成したらstd::pair<>、それをどこに保存して、に挿入できるようstd::inserterにしstd::mapますか?

4

1 に答える 1

14

C++ std で達成できるタスクにブーストを使用するのはなぜですか? insert_iterator で istream_iterator を使用するだけです。これを行うには、 std 名前空間 stream<<と '>>' 演算子でpair<string,string>. このようなもの:

namespace std {
// I am not happy that I had to put these stream operators in std namespace.
// I had to because otherwise std iterators cannot find them 
// - you know this annoying C++ lookup rules...
// I know one solution is to create new type inter-operable with this pair...
// Just to lazy to do this - anyone knows workaround?
istream& operator >> (istream& is, pair<string, string>& ps)
{
   return is >> ps.first >> ps.second;
}
ostream& operator << (ostream& os, const pair<const string, string>& ps)
{
   return os << ps.first << "==>>" << ps.second;
}
}

そして使用法:

標準挿入イテレータ:

  std::map<std::string, std::string> mps;
  std::insert_iterator< std::map<std::string, std::string> > mpsi(mps, mps.begin());

std istream イテレータ:

  const std::istream_iterator<std::pair<std::string,std::string> > eos; 
  std::istream_iterator<std::pair<std::string,std::string> > its (is);

読む:

  std::copy(its, eos, mpsi);

書き込み (ボーナス):

  std::copy(mps.begin(), mps.end(),   std::ostream_iterator<std::pair<std::string,std::string> >(std::cout, "\n"));

ideone での作業例

于 2012-09-28T20:34:12.930 に答える