C++0x way to replace for(int i;;) range loops with range-based for-loop

走远了吗. 提交于 2020-01-11 02:53:04

问题


So I've been getting into the new C++ using GCC 4.6 which now has range-based for-loops. I've found this really nice for iterating over arrays and vectors.

For mainly aesthetic reasons I wondered if there was a way to use this to replace the standard

for(int i = min; i < max; i++) {}

with something like

for(int& i : std::range(min, max)) {}

Is there something natively built into the new C++ standard that allows me to do this? Or do I have to write my own range/iterator class?


回答1:


I don't see it anywhere. But it would be rather trivial:

class range_iterator : public std::input_iterator<int, int> {
    int x;
public:
    range_iterator() {}
    range_iterator(int x) : x(x) {}
    range_iterator &operator++() { ++x; return *this; }
    bool operator==(const range_iterator &r) const { return x == r.x; }
    int operator*() const { return x; }
};
std::pair<range_iterator, range_iterator> range(int a, int b) {
    return std::make_pair(range_iterator(a), range_iterator(b));
}

should do the trick (off the top of my head; might need a little tweaking). Pair of iterators should already be range, so I believe you shouldn't need to define begin and end yourself.



来源:https://stackoverflow.com/questions/4930096/c0x-way-to-replace-forint-i-range-loops-with-range-based-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!