c++ - 如何将此 for 循环更改为 for_each 循环?

标签 c++

如何将其转换为 for_each循环?

template <typename Container>
void draw_all(const Container &c, const rectangle &w)
{
    complex<double> bl, tr;
    bl = w.get_bl();
    tr = w.get_tr();

    for (typename Container::const_iterator p= c.begin(); p != c.end(); p++)
    {
        if((*p)->inside_window(bl,tr))
            (*p)->draw();
    }
}

我正在尝试:for_each(c.begin(), c.end(), w.inside_window(w.get_bl(),w.get_tr()));

我收到错误:将“const rectangle”作为“virtual bool rectangle::inside_window(const std::complex&, const std::complex&)”的“this”参数赋值会丢弃限定符 [-fpermissive]

编辑:在 window() 内

bool rectangle::inside_window(const complex<double> &_bl, const complex<double> &_tr)
{
    if(_bl.real() > bl.real() || _tr.real() > tr.real() || _bl.imag() > bl.imag() || _tr.imag() > tr.imag())
    {
        return false;
    }
    else
        return true;

    cout.flush();
}

for_each():

template<typename InputIter, typename UnaryFunction>
UnaryFunction for_each(InputIter first, InputIter last, UnaryFunction fn)
{
    while (first != last)
        fn(* first++); // Increment first but dereference its old value.
    return fn;
}

最佳答案

您需要将 rectangle::inside_window() 声明为 const 方法:

virtual bool inside_window(const std::complex&, const std::complex&) const;
                                                                  // ^^^^^

这使得 this 的类型为 const rectangle* 而不仅仅是 rectangle*,它允许 inside_window()const rectangle 上调用,因为它必须在 for_each() 中。

但是,您的逻辑有缺陷:如果您想测试inside_window() 的结果并有条件地调用draw(),那么使用 for_each() 做到这一点的唯一方法是使用辅助方法,或者作为仿函数:

struct draw_visible : public std::unary_function<rectangle, void> {

    const std::complex<double> bl, tr;

    draw_visible(const std::complex<double>& bl, const std::complex<double> tr)
        : bl(bl), tr(tr) {}

    void operator()(const rectangle& r) const {
        if (r.inside_window(bl, tr))
            r.draw();
    }

};

template<class Container>
void draw_all(const Container& c, const rectangle& w) {
     std::for_each(c.begin(), c.end(), draw_visible(w.get_bl(), w.get_tr()));
}

或者作为 lambda:

template<class Container>
void draw_all(const Container& c, const rectangle& w) {
    std::for_each(c.begin(), c.end(), [&w](const rectangle& r) {
        if (r.inside_window(w.get_bl(), w.get_tr())
            r.draw();
    });
}

此外,您可能不应该使用 std::complex 来建模点。自定义结构在语义上更合适:

// A basic mutable 2D double vector.
struct point {
    double x, y;
};

关于c++ - 如何将此 for 循环更改为 for_each 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8335328/

相关文章:

c++ - 使用变体时,模板化的 child 不被接受为 parent

c++ - C++静态成员函数的实现

c++ - 需要有关跳过列表的信息

c++ - 多个函数调用对相同的输入参数返回不同的结果

c++ - 覆盖具有不同返回类型的虚函数会引发私有(private)继承错误

c++ - 为什么会出现段错误(数组作为类的元素)?

c++ - VC++ 允许对 STL 容器使用 const 类型。为什么?

C++ MSXML2 - 从 XML 中删除 namespace

c++ - 使用无符号数进行图像边界检查

c++ - glDrawElements,为什么会导致程序停止工作?