【发布时间】:2009-01-20 14:26:55
【问题描述】:
如何通过 boost::ptr_map 有效地使用 BOOST_FOREACH(字符数/可读性)?
Kristo 在他的 answer 中演示了可以将 BOOST_FOREACH 与 ptr_map 一起使用,但与使用迭代器迭代 ptr_map 相比,它并没有真正为我节省任何打字(或使我的代码更易读):
typedef boost::ptr_container_detail::ref_pair<int, int* const> IntPair;
BOOST_FOREACH(IntPair p, mymap) {
int i = p.first;
}
// vs.
boost::ptr_map<int, T>::iterator it;
for (it = mymap.begin(); it != mymap.end(); ++it) {
// doSomething()
}
以下代码符合我的期望。它遵循如何将 BOOST_FOREACH 与 std::map 一起使用的标准方法。不幸的是,这不能编译:
boost::ptr_map<int, T> mymap;
// insert something into mymap
// ...
typedef pair<int, T> IntTpair;
BOOST_FOREACH (IntTpair &p, mymap) {
int i = p.first;
}
【问题讨论】: