为什么要使用 boost 来完成可以用 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);
Reading:
std::copy(its, eos, mpsi);
写作(奖金):
std::copy(mps.begin(), mps.end(), std::ostream_iterator<std::pair<std::string,std::string> >(std::cout, "\n"));
ideone 的工作示例 http://ideone.com/ZbqWI