v88*_*891 5 c++ boost boost-foreach
我有一个迭代的矢量.向量的最后一个元素是特例,我想分别测试它.例如,我可以这样做:
for (iterator = vector.begin(); iterator != vector.end(); ++iterator) {
if ((iterator + 1) == (vector.end())) {
...
} else {
...
}
}
Run Code Online (Sandbox Code Playgroud)
我想用BOOST_FOREACH宏替换迭代器.可以对最终元素进行类似的测试吗?
ybu*_*ill 13
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
}
Run Code Online (Sandbox Code Playgroud)
由于BOOST_FOREACH使用范围,您可以将矢量分成您想要正常使用的范围(在BOOST_FOREACH循环中)并且您想要特别处理它:
#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;
}
Run Code Online (Sandbox Code Playgroud)