简体   繁体   English

range-for循环到底能做什么?

[英]What does range-for loop exactly do?

I'm working on a snake game program. 我正在开发蛇游戏程序。 I use a deque of Body in class Snake to represent a snake and of course Body is a struct I have defined. 我在Snake类中使用Body的双端队列来表示蛇,当然Body是我定义的结构。 Here is part of the code: 这是代码的一部分:

struct Body {        // one part of snake body
    int x, y, direction;
    Body() : x(0), y(0), direction(UP) { }
    Body(int ix, int iy, int id) : x(ix), y(iy), direction(id) { }
};

class Snake {
protected:
    std::deque<Body> body;
    // other members
public:
    auto begin()->std::deque<Body>::const_iterator const { return body.cbegin(); }
    auto end()->std::deque<Body>::const_iterator const { return body.cend(); }
    // other members
};

And in another function construct_random_food I need to generate a food and make sure it does not coincide with the snake. 在另一个函数construct_random_food中,我需要生成一个食物,并确保它与蛇不重合。 Here's the function definition: 这是函数定义:

Food construct_random_food(int gameSize, const Snake& snake) {
    static std::random_device rd;
    static std::uniform_int_distribution<> u(2, gameSize + 1);
    static std::default_random_engine e(rd());
    Food f;
    while (1) {
        f.x = u(e) * 2 - 1;
        f.y = u(e);
        bool coincide = 0;
        for (const auto& bd : snake) // This causes an error.
            if (bd.x == f.x && bd.y == f.y) {
                coincide = 1; break;
            }
        if (!coincide) break;
    }
    return f;
}

An error is caused at the range-based for-loops line. 在基于范围的for循环行中导致错误。 It says that I'm trying to cast const Snake to Snake& (casting a low-level const away). 它表示我正在尝试将const Snake强制转换为Snake&(将低级const转换掉)。 I fix the problem by rewriting that line like this: 我通过重写该行来解决此问题:

for (const auto& fd : const_cast<Snake&>(snake))

So I'm wondering what exactly a range-for do and what it needs. 所以我想知道范围是做什么的,它需要什么。 Does the error have anything to do with the begin() function in class Snake? 该错误与Snake类中的begin()函数有关吗?

The problem is that your begin and end functions are not const. 问题是您的beginend函数不是const。

auto begin()->std::deque<Body>::const_iterator const { return body.cbegin(); }
            // this applies to the return type ^^^^^

You've applied the const qualifier to the return type, not to the calling object. 您已将const限定符应用于返回类型,而不是调用对象。 Put the const qualifier before the trailing return type. const限定词放在尾随返回类型之前。

auto begin() const ->std::deque<Body>::const_iterator { return body.cbegin(); }

You can see the correct order in which you should place function qualifiers here: http://en.cppreference.com/w/cpp/language/function 您可以在此处看到放置函数限定符的正确顺序: http : //en.cppreference.com/w/cpp/language/function

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

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