阅读键 - 值对的文件中的一个std ::地图(reading a file of key-valu

2019-09-23 04:33发布

我有一个Visual Studio 2008的C ++ 03项目中,我想读键值对的文件中的一个std ::地图。 要做到这一点,我创建了一个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::inserterstd::map

Answer 1:

为什么使用它可以用C ++的std东西来实现任务提升? 只要使用istream_iterator与insert_iterator。 要做到这一点,你必须在std名字空间流定义<<和“>>”运营商为您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插入迭代器:

  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例子



文章来源: reading a file of key-value pairs in to a std::map