是否有可能在 BOOST_FOREACH 循环中使用带有 std::distance 的differ_type?
#define foreach_ BOOST_FOREACH
class iObj { /* some def and impl */ };
typedef set<iObj*> iSet;
int main() {
iSet *iobjs = new iSet();
// fill set with integers
for( int i=0; i<100; i++) {
iobjs->insert( new iObj(i+1+i*2) );
}
// output content of set
cout << "print objects ASC" << endl;
for( iSet::const_iterator oIt = iobjs->begin();
oIt != iobjs->end(); ++oIt) {
iSet::difference_type oIndex = std::distance( iobjs->begin(), oIt );
if( oIndex < 50 ) {
cout << " #" << oIndex << ": " << **oIt << endl;
} else {
break;
}
}
// output with BOOST
cout << "print objects ASC" << endl;
foreach_( iObj *o, *iobjs ) {
cout << *o << endl;
// no access of index?
}
delete iobjs;
return 0;
}
更方便地显示例如大集合的前 50 个条目,而不是全部内容,并且使用 std::distance 不需要插入新的计数器变量并由我自己增加它