Boost.Foreach

BOOST_FOREACH简化了C++的循环遍历序列元素。

支持的序列类型:Boost.Range识别的序列

  • STL容器
  • 数组
  • Null-terminated String
  • std::pair of iterators
#include <string>
#include <iostream>
#include <boost/foreach.hpp>

int main()
{
    std::string hello( "Hello, world!" );

    BOOST_FOREACH( char ch, hello )
    {
        std::cout << ch;
    }

    return 0;
}

遍历STL容器:

std::list<int> list_int( /*...*/ );
BOOST_FOREACH( int i, list_int )
{
    // do something with i
}

遍历数组,包含short到int的协变(covariance):

short array_short[] = {1,2,3};
BOOST_FOREACH( int i, array_short )
{
    // The short was implicitly converted to an int
}

打破循环:

std::deque<int> deque_int( /*...*/ );
int i = 0;
BOOST_FOREACH( i, deque_int )
{
    if( i == 0 ) return;
    if( i == 1 ) continue;
    if( i == 2 ) break;
}

遍历引用并修改:

short array_short[] = { 1, 2, 3 };
BOOST_FOREACH( short & i, array_short )
{
    ++i;
}
// array_short contains {2,3,4} here

嵌套遍历:

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

直接遍历返回值:

extern std::vector<float> get_vector_float();
BOOST_FOREACH( float f, get_vector_float() )
{
    // Note: get_vector_float() will be called exactly once
}

反向遍历:

std::list<int> list_int( /*...*/ );
BOOST_REVERSE_FOREACH( int i, list_int )
{
    // do something with i
}

美化一下名字:

#define foreach_         BOOST_FOREACH
#define foreach_r_       BOOST_REVERSE_FOREACH
原文地址:https://www.cnblogs.com/chenkkkabc/p/3195908.html