将键值对文件读入 std::map
reading a file of key-value pairs in to a std::map
我有一个Visual Studio 2008 C++03项目,我想将键值对的文件读入std::map。为此,我创建了一个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
中?
为什么要对可以用C++标准的东西完成的任务使用 boost?只需将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::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 的工作示例
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 使用一个考虑到std::map中键值的滚动或换行的键
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- C++如何创建 std::map
- 从其他容器中移动构造"std::map"
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- C++中 std::map 的运行时复杂度是多少?
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 使用重载 [] 运算符返回 std::map() 的可赋值
- std::map, std::unordered_map - 缩小初始值设定项列表中的转换范围
- C++ 使用枚举类对象分配 std::map 值
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- std::map:当元素不可默认构造时创建/替换元素
- Arduino编译器和STL:使用std::vector和std::map