简体   繁体   中英

How to use the range based for loop iterator?

I have this code for an insertion sort algorithm and I was wondering whether there is a range based for loop equivalent to the for loop that I'm using.

I'm sort of confused with how the range based loop iterator works as compared to the regular STL container iterators. just plainly substituting for(auto it:x) clearly doesn't work.

Mainly, my question is how I may dereference that range based iterator to get the corresponding array value. this is my insertion sort code:


for (auto it = x.begin(); it != x.end();it++)
 {
        auto insertloc = std::upper_bound(x.begin(), it, *it);

        std::rotate(insertloc, it, it + 1);
}

This code works just fine but I just want to know if I can replace that for loop with a range based one.

I want to replace that for loop with a range based one.

That would not work for your use case. The range-for loop works when you only need the value of the object that you get by dereferencing the iterator. It is not going to work for your case since you are using the iterator in the loop. There is no standard mechanism by which you can get the iterator from the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM