C ++用宏实现范围循环

时间:2014-03-02 09:59:02

标签: c++

我尝试使用基本宏在C ++中进行for range循环的基本实现,以便您可以这样做:

C ++ 11

std::vector<int> v;
for(int i = 0; i < 10; ++i)
{
    v.push_back(i);
}
for(auto &a : v)
{, 
    std::cout << a << "\n";
}

C ++ 03或更早版

std::vector<int> v;
for(int i = 0; i < 10; ++i)
{
    v.push_back(i);
}
FOR_RANGE(std::vector<int>, x, v)
{
    std::cout << x << "\n";
}

然而,它没有用,因为我无法实现var部分:我已经在循环中指定了初始化类型:

#define FOR_RANGE(container_type, var, container) for(container_type::iterator iter = container.begin() /* somewhere implement the var bit */; iter != container.end(); ++iter)

我该怎么办?

注意:我不是在寻找for_each算法。

3 个答案:

答案 0 :(得分:0)

#define FOR_RANGE(C_type, it, C) for(C_type::iterator it=C.begin(); it!=C.end(); ++it)


FOR_RANGE(std::vector<int>, a, v)
{
    std::cout << *a << std::endl;
}

答案 1 :(得分:0)

这样做你想要的吗?

#define FOR_RANGE(container_type, var, container) \
  for(container_type::iterator var = container.begin(); var != container.end(); ++var)

答案 2 :(得分:0)

以下是rang()

中的Python函数实现
#include <algorithm>
#include <iostream>
#include <iterator>

using namespace std;

template <typename T>
class range_type {
public:
    class range_iterator {
    public:
        typedef T value_type;
        typedef T* pointer;
        typedef T& reference;
        typedef T difference_type;
        typedef forward_iterator_tag iterator_category;

        range_iterator(T v) : v_(v) {}
        T operator*() const { return v_; }
        range_iterator operator++() { ++v_; return *this; }
        range_iterator operator++(int) { range_iterator copy(*this); ++v_; return copy; }
        bool operator==(const range_iterator &other) const { return v_ == other.v_; }
        bool operator!=(const range_iterator &other) const { return v_ != other.v_; }
    private:
        T v_;
    };

    range_type(T lower, T upper) : lower_(lower), upper_(upper) {}
    range_iterator begin() const { return range_iterator(lower_); }
    range_iterator end() const { return range_iterator(upper_); }

private:
    T lower_, upper_;
};

template <typename T>
range_type<T> range(T lower, T upper) { return range_type<T>(lower, upper); }

template <typename Container, typename UnaryPredicate>
bool none_of(const Container& c, UnaryPredicate pred) { return none_of(c.begin(), c.end(), pred); }

template <typename Container, typename DestIterator, typename UnaryPredicate>
void copy_if(const Container& c, DestIterator d, UnaryPredicate pred) { copy_if(c.begin(), c.end(), d, pred); }

int main() {
    copy_if(range(2, 101), ostream_iterator<int>(cout, " "), [](int x){ return none_of(range(2, x), [x](int y) { return x % y == 0; }); });
    return 0;
}