在BOOST foreach中使用difference_type

using difference_type in BOOST foreach

本文关键字:difference type BOOST foreach      更新时间:2023-10-16

是否有可能在BOOST_FOREACH循环中使用difference_type和std::distance?

#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,不需要插入新的计数器var并将其递增myself

您想知道BOOST_FOREACH循环体中的循环迭代吗?不,你不能那样做。使用基于C++11范围的for循环也无法做到这一点。为此,普通的for循环是最好的。(请,请,请停止使用BOOST_FOREACH。C++11基于范围的for是这个主题的最终决定。)

我还应该指出,您的代码效率低下是不必要的。std::set的迭代器不是随机访问的,所以std::distance是O(N)。更好的方法是保留一个单独的循环计数器,并在循环中每次递增。

此外,您的代码正在泄漏内存。尽管您正在删除new’ed的std::set,但您并没有删除new’ed的所有iObj对象。在您所展示的代码中,似乎不需要动态分配任何内容。试着只按值存储对象,而不是new对它们进行存储,并使用本地std::set堆栈变量。你会给自己省去一个麻烦的世界。