Access index in range-for loop

后端 未结 6 488
忘了有多久
忘了有多久 2020-12-24 11:44

I have a vector of objects and am iterating through it using a range-for loop. I am using it to print a function from the object, like this:

vector

        
6条回答
  •  抹茶落季
    2020-12-24 12:13

    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.

提交回复
热议问题