且构网

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

范围循环中的访问索引

更新时间:2022-06-24 02:53:41

您不能。 index 是向量的特定概念,而不是集合的通用属性。另一方面,基于范围的循环是遍历 any 集合的每个元素的通用机制。

You can't. The index is a specific notion to a vector, and not a generic property of a collection. The range-based loop on the other hand is a generic mechanism for iterating over every element of any collection.

如果您要使用特定容器实现的详细信息,只需使用普通循环即可:

If you do want to use the details of your particular container implementation, just use an ordinary loop:

for (std::size_t i = 0, e = v.size(); i != e; ++i) { /* ... */ }

重复这一点:基于范围的循环用于处理任何集合的每个元素,其中集合本身无关紧要,并且在循环体内从未提及容器。它只是工具箱中的另一种工具,因此您不必***将其用于所有功能。相比之下,如果您要对集合进行突变(例如,删除或随机排列元素),或者要使用有关集合结构的特定信息,请使用普通循环。

To repeat the point: Range-based loops are for manipulating each element of any collection, where the collection itself doesn't matter, and the container is never mentioned inside the loop body. It's just another tool in your toolbox, and you're not forced to use it for absolutely everything. By contrast, if you either want to mutate the collection (e.g. remove or shuffle elements), or use specific information about the structure of the collection, use an ordinary loop.