Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 564
v8891 Avatar asked May 11 '11 06:05

v8891


2 Answers

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
}
like image 95
Yakov Galka Avatar answered Nov 12 '22 10:11

Yakov Galka


Since BOOST_FOREACH works with ranges you can split your vector into the range you want to work with normally (in the BOOST_FOREACH loop) and whose you want to treat specially:

#include <stdio.h>
#include <vector>

#include "boost/foreach.hpp"
#include "boost/range.hpp"

using namespace std;

int main () {
    vector<int> foo;

    foo.push_back(1);
    foo.push_back(2);
    foo.push_back(3);
    foo.push_back(4);

    vector<int>::iterator special_item(foo.end() - 1);
    boost::sub_range< vector<int> > normal_items(foo.begin(), special_item);

    BOOST_FOREACH( int i, normal_items) {
        printf( "%d ", i);
    }

    printf( "\nspecial item: %d\n", *special_item);

    return 0;
}
like image 21
Michael Burr Avatar answered Nov 12 '22 10:11

Michael Burr