c++boostboost-foreach

How can I test for the last element in a vector when using BOOST_FOREACH?


I have a vector which I iterate over. The final element of the vector is special case, and I'd like to test for it separately. For example, I may do something as such:

for (iterator = vector.begin(); iterator != vector.end(); ++iterator) {
    if ((iterator + 1) == (vector.end())) {
        ...
    } else {
        ...
    }
}

I would like to replace the iterator with the BOOST_FOREACH macro. Can a similar test for the final element be done?


Solution

  • if(!vec.empty())
    {
        BOOST_FOREACH(int e, boost::make_iterator_range(vec.begin(), vec.end()-1))
        {
            // Handle each element but the last
        }
    
        // Handle last element here
    }