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?
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
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With