用BOOST_FOREACH简化遍历操作

来源:互联网 发布:mac的dns怎么设置最快 编辑:程序博客网 时间:2024/05/17 02:38

BOOST_FOREACH可以方便的遍历STL容器.

只需要头文件:

#include <boost/foreach.hpp>

然后遍历容器vector/list/set/deque/stack/queue都是类似的:

vector<int32_t> _v;
BOOST_FOREACH(int32_t value,_v)
{
//这里就可以访问value
}

同时元素还支持引用,const,比如上面代码还可以写成:

vector<int32_t> _v;

BOOST_FOREACH(int32_t
& value,_v)
{
//这里就可以修改/访问value
}

如果元素内容是结构体之类,引用可以防止拷贝~~

对于map的访问有一点特殊,因为map的元素是std::pair<T1,T2>,所以需要写成这样:

复制代码
std::map<int32_t,int32_t> _map;
typedef const std::map<int32_t, int32_t>::value_type const_pair;
BOOST_FOREACH(const_pair
& node,_map)
{
//这里就可以访问node的元素
int32_t key = node.first;
int32_t value 
= node.second;
}
复制代码

multimap么暂时还没用过,不过相信也是类似的...感觉multimap有一点类似于map<key,set<value> > :-D

BOOST_FOREACH是正向的迭代,逆向的是BOOST_REVERSE_FOREACH。

看看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实现,太牛了。



0 0