问题描述
如何通过 boost::ptr_map 有效地使用 BOOST_FOREACH(字符数/可读性)?
How can I use BOOST_FOREACH efficiently (number-of-character/readability-wise) with a boost::ptr_map?
Kristo 在他的回答中证明这是可能的将 BOOST_FOREACH 与 ptr_map 一起使用,但与使用迭代器迭代 ptr_map 相比,它并没有真正为我节省任何输入(或使我的代码真正更具可读性):
Kristo demonstrated in his answer that it is possible to use BOOST_FOREACH with a ptr_map, but it does not really save me any typing (or makes my code really more readable) than iterating over the ptr_map with an iterator:
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 一起使用的标准方法.不幸的是,这不能编译:
The following code is somewhere along the lines what I wish for. It follows the standard way on how to use BOOST_FOREACH with a std::map. Unfortunately this does not compile:
boost::ptr_map<int, T> mymap;
// insert something into mymap
// ...
typedef pair<int, T> IntTpair;
BOOST_FOREACH (IntTpair &p, mymap) {
int i = p.first;
}
推荐答案
作为 STL 风格的容器,指针容器有一个 value_type
类型定义,你可以使用:
As STL style containers, the pointer containers have a value_type
typedef that you can use:
#include <boost/ptr_container/ptr_map.hpp>
#include <boost/foreach.hpp>
int main()
{
typedef boost::ptr_map<int, int> int_map;
int_map mymap;
BOOST_FOREACH(int_map::value_type p, mymap)
{
}
}
我发现为容器使用 typedef 会使代码更容易编写.
I find that using a typedef for the container makes the code a lot easier to write.
另外,你应该尽量避免在 boost 中使用 detail
命名空间的内容,这是一个包含实现细节的 boost 约定.
Also, you should try to avoid using the contents of detail
namespaces in boost, it's a boost convention that they contain implementation details.
这篇关于如何将 BOOST_FOREACH 与 boost::ptr_map 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!