Section 5.2.  Sequences and Algorithms
Team LiB
Previous Section Next Section

5.2. Sequences and Algorithms

Most of the algorithms in the MPL operate on sequences. For example, searching for a type in a vector looks like this:



    typedef mpl::vector<char,short,int,long,float,double> types;





    // locate the position of long in types


    typedef mpl::find<types, long>::type long_pos;



Here, find accepts two parametersa sequence to search (types) and the type to search for (long)and returns an iterator indicating the position of the first element in the sequence that is identical to long. Except for the fact that mpl::find takes a single sequence parameter instead of two iterators, this is precisely how you would search for a value in a std::list or std::vector:



    std::vector<int> x(10);


    std::vector<int>::iterator five_pos


         = std::find(x.begin(), x.end(), 5);



If no matching element exists, mpl::find returns the sequence's past-the-end iterator, which is quite naturally accessed with the mpl::end metafunction:



    // assert that long was found in the sequence


    typedef mpl::end<types>::type finish;


    BOOST_STATIC_ASSERT((!boost::is_same<long_pos, finish>::value));



A similar begin metafunction returns an iterator to the beginning of the sequence.

    Team LiB
    Previous Section Next Section