在BOOST foreach中使用difference_type
using difference_type in BOOST foreach
是否有可能在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
堆栈变量。你会给自己省去一个麻烦的世界。
相关文章:
- Difference in displaying cv2 Mat
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 在 QVector<std::unique_ptr 上使用 std::find<Type>>
- 在类型和包装器之间reinterpret_cast是否安全<Type>?
- 使用 cmake 的 Linux 终端上的"Conversion to non-scalar type is requested"错误
- 控制到达非空函数clang(-Wreturn-type)的末尾
- std::unordered_map 类型对象声明期间出现"field has incomplete type"错误
- 将系数存储在头文件的数组中("does not name a type"错误)
- 尝试打开 ifstream 时出现"Incomplete type"错误
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 在"结构提升::enable_if<提升::is_pod<T>,无效>"中没有名为"type"的类型
- "Missing type specifier - int assumed"无法通过向主函数添加"return 0"来解决
- OpenCV CV_16F type
- C++ "错误:在'类 std::result_of< ... >"中没有名为'type'的类型"
- 将内存分配返回值强制转换为 TYPE 数组
- C++ 一个lambda浅拷贝const Type&如果它被赋予一个命名捕获,如[copy=val](){}?
- reference_wrapper导致"incomplete type is not allowed"
- 继承类时"invalid use of incomplete type ‘class tree_node_t’"
- 由于"error C4430: missing type specifier - int assumed. Note: C++ does not support default-int",我现在无法编
- 如何解决"'mutex' in namespace 'std' does not name a type"?