BOOST_FOREACH可以方便的遍历STL容器.node
仅仅需要头文件:oop
#include <boost/foreach.hpp>this
而后遍历容器vector/list/set/deque/stack/queue都是相似的:spa
同一时候元素还支持引用,const,比方上面代码还可以写成:设计
假设元素内容是结构体之类,引用可以防止拷贝~~调试
对于map的訪问有一点特殊,因为map的元素是std::pair<T1,T2>,因此需要写成这样:code
multimap么临时还没用过,只是相信也是相似的...感受multimap有一点相似于map<key,set<value> > :-Dblog
BOOST_FOREACH是正向的迭代,逆向的是BOOST_REVERSE_FOREACH。get
看看BOOST_FOREACH的实现吧:编译器
///////////////////////////////////////////////////////////////////////////////
// BOOST_FOREACH
//
// For iterating over collections. Collections can be
// arrays, null-terminated strings, or STL containers.
// The loop variable can be a value or reference. For
// example:
//
// std::list<int> int_list(/*stuff*/);
// BOOST_FOREACH(int &i, int_list)
// {
// /*
// * loop body goes here.
// * i is a reference to the int in int_list.
// */
// }
//
// Alternately, you can declare the loop variable first,
// so you can access it after the loop finishes. Obviously,
// if you do it this way, then the loop variable cannot be
// a reference.
//
// int i;
// BOOST_FOREACH(i, int_list)
// { ... }
//
#define BOOST_FOREACH(VAR, COL) /
BOOST_FOREACH_PREAMBLE() /
if (boost::foreach_detail_::auto_any_t _foreach_col = BOOST_FOREACH_CONTAIN(COL)) {} else /
if (boost::foreach_detail_::auto_any_t _foreach_cur = BOOST_FOREACH_BEGIN(COL)) {} else /
if (boost::foreach_detail_::auto_any_t _foreach_end = BOOST_FOREACH_END(COL)) {} else /
for (bool _foreach_continue = true; /
_foreach_continue && !BOOST_FOREACH_DONE(COL); /
_foreach_continue ?
BOOST_FOREACH_NEXT(COL) : (void)0) /
if (boost::foreach_detail_::set_false(_foreach_continue)) {} else /
for (VAR = BOOST_FOREACH_DEREF(COL); !_foreach_continue; _foreach_continue = true)
#endif
//代码一共同拥有800多行。我列出了最后的凝视和定义。
我认为BOOST_FOREACH有点搞过头了。手写for的循环。最多也就两行。为何要为形式上的简单而引入如此多的定义和编译器解析。而且这仍是个宏。我不是反对宏,仅仅是认为宏在这个地方没带来太多优势,反而添乱。调试的噩梦,郁闷死。
不是每个库都是那么精彩和有用的。std::vector<bool>的特化。std::auto_ptr的设计也都不那么让人温馨。
保持脑壳清醒,有选择的使用类库吧。
最后。仍是要感叹一下BOOST_FOREACH实现。太牛了。