C++ 基于数值的range-base for
本文最后更新于 2122 天前,其中的信息可能已经有所发展或是发生改变。

内容纲要

C++11以后支持range-base for
ES6以后,JavaScript在使用for的时候可以这么写:

const obj = {
    a:'b',
    b:'c'
};

for(let i of obj) {
    console.log(i);
}
/* output:
b
c
*/

而在C++中 则写成:

vector<int>vec;
vec.push(1);
vec.push(2)l
for(auto i:vec) {
    cout << i << endl;
}
/* output
1
2
*/

而我们在数值范围的循环的时候,range-base for就用不了了.
在Python中我们可以使用

for i in range(0,5):
    print i

来实现基于范围的range-base for

因此为了在C++中实现类似的功能,我们可以自定义一个class并在其中封装iterator来实现。


#pragma GCC optimize("O3")

#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <array>
#include <iterator>

using namespace std;

class range {
public:
    class iterator {
        friend class range;

    public:
        int operator*() const { return i_; }

        iterator &operator++() {
            ++i_;
            return *this;
        }

        iterator operator++(int) {
            iterator copy(*this);
            ++i_;
            return copy;
        }

        bool operator==(const iterator &other) const { return i_ == other.i_; }

        bool operator!=(const iterator &other) const { return i_ != other.i_; }

    protected:
        iterator(int start) : i_(start) {}

    private:
        int i_;
    };

    iterator begin() const { return begin_; }

    iterator end() const { return end_; }

    range(int begin, int end) : begin_(begin), end_(end) {}

private:
    iterator begin_;
    iterator end_;
};

template<typename T>
class reverse_iterator_class {
public:
    explicit reverse_iterator_class(const T &t) : t(t) {}

    typename T::const_reverse_iterator begin() const { return t.rbegin(); }

    typename T::const_reverse_iterator end() const { return t.rend(); }

private:
    const T &t;
};
using ll = long long;

template<typename T>
reverse_iterator_class<T> reverse(const T &t) {
    return reverse_iterator_class<T>(t);
}

于是,我们就可以这么用:

for(auto i:range(0,5)) {
    cout << i << endl;
}
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇