简体   繁体   English

如何使用基于范围的循环迭代器?

[英]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. 我有用于插入排序算法的这段代码,我想知道是否存在与我使用的for循环等效的for循环范围。

I'm sort of confused with how the range based loop iterator works as compared to the regular STL container iterators. 与常规STL容器迭代器相比,我对基于范围的循环迭代器的工作方式感到困惑。 just plainly substituting for(auto it:x) clearly doesn't work. 只是简单地用for(auto it:x)代替显然是行不通的。

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. 这段代码很好用,但是我只想知道是否可以将for循环替换为基于范围的循环。

I want to replace that for loop with a range based one. 我想用基于范围的范围替换for循环。

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. 当您只需要通过取消引用迭代器而获得的对象的值时,range-for循环将起作用。 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. 没有标准机制可以从值中获取迭代器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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