且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++ 中类似 Python 的循环枚举

更新时间:2023-11-14 22:20:10

正如@Kos 所说,这是一件如此简单的事情,我真的不认为有必要进一步简化它,个人只会坚持传统的使用索引循环,除了我会放弃 std::vector::size_type 并简单地使用 std::size_t:

As @Kos says, this is such a simple thing that I don't really see the need to simplify it further and would personally just stick to the traditional for loop with indices, except that I'd ditch std::vector<T>::size_type and simply use std::size_t:

for(std::size_t i = 0; i < v.size(); ++i)
    foo(v[i], i);

我不太热衷于解决方案 2.它需要(有点隐藏)随机访问迭代器,这不允许您轻松交换容器,这是迭代器的强项之一.如果您想使用迭代器并使其通用(并且当迭代器不是随机访问时可能会导致性能下降),我建议使用std::distance:

I'm not too keen on solution 2. It requires (kinda hidden) random access iterators which wouldn't allow you to easily swap the container, which is one of the strong points of iterators. If you want to use iterators and make it generic (and possibly incur a performance hit when the iterators are not random access), I'd recommend using std::distance:

for(auto it(v.begin()); it != v.end(); ++it)
    foo(*it, std::distance(it, v.begin());