boost_foreach

example 1:
string str("Hello, world!");
BOOST_FOREACH(char c, str)
{
    cout << c;
}
它相当于:
string str("Hello, world!");
for(int i = 0; i < str.length(); ++i)
{
    char c = str[i];
    cout << c;
}

example 2:
int arr[] = {1, 3, 5, 2, 0};
BOOST_FOREACH(int & a, arr)
{
    ++a;
    ....
}
arr中的值被改变了,如果是 int a,则arr中的值不会变。

它相当于:
int arr[] = {1, 3, 5, 2, 0};
for(int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i)
{
    int & a = arr[i];
    ++a;
    ...
}

example 3:
std::vector<std::vector<int> > matrix_int;
BOOST_FOREACH( std::vector<int> & row, matrix_int )
    BOOST_FOREACH( int & i, row )
        ++i;

to make the BOOST_FOREACH shorter:
#define foreach BOOST_FOREACH
#define rforeach BOOST_REVERSE_FOREACH

inlude <boost/foreach.hpp> when using it, of course.

It's so easy!
posted @ 2011-07-08 13:49  我的小屋子  阅读(201)  评论(0)    收藏  举报