deque迭代器超出范围

问题描述 投票:0回答:2

我试图通过一些类似数组的对象进行洗牌。我想在前面添加一个值,然后弹出最后一个值。我根据我在其他帖子中看到的建议尝试使用deque,但我仍然遇到错误。有任何想法吗?我是C ++的新手,虽然我可以尝试写这个问题,但我想知道它在哪里,所以我可以解决它。

我得到一个:无法从visual studio中寻找deque迭代器超出范围的调试错误。

导致问题的功能:

(我最初使用矢量)

void vector_pusher(deque <int> &v, int new_val ) { 
v.push_front(new_val);
v.erase(v.begin() + 3);
}

这是我的其余代码(可能是构造函数问题?):

#include "lock.h"
#include <deque>
#include <iostream>
using namespace std;

lock::lock(int x, int y, int z) {
    is_closed = true;
    current_top = 0;
    comb[0] = x % MAX_VAL;
    comb[1] = y % MAX_VAL;
    comb[2] = z % MAX_VAL;
    deque <int> trycomb = { 1, 1, 1 };
    deque <char> trydir = { 'q', 'q', 'q' };
    deque <int> rot = { 1,1,1 };
}

void lock::turn(int input, char direction, int rotation) {

    vector_pusher(trydir, direction);
    vector_pusher(trycomb, input);
    vector_pusher(rot, rotation);

}

在lock.h中:

 public:
        lock(int, int, int);
        void turn(int, char, int);
        \* these functions are defined elsewhere and doing fine
        void new_comb(int, int, int);
        void open_close();
        bool lock_status() const;
        *\

        //entered combination
        deque <int> trycomb;

        // entered diections
        deque <char> trydir;

        //entered rotations (0 is directly too, 1 is around once)
        deque <int> rot;



    private:
        // current correct combo
        deque <int> comb = {0, 0, 0};

        //top val
        //this is unessesary
        int current_top;

        //open-ness state of lock
        bool is_closed;

        //needed directions
        deque <char> dir = {'r', 'l', 'r'};

谢谢您的帮助!

c++ visual-studio
2个回答
0
投票

看起来你永远不会在你的构造函数中初始化trycombtrydirrot。您在构造函数中声明具有相同名称的局部变量,这些变量会影响lock类的成员变量。您的构造函数应如下所示:

lock::lock(int x, int y, int z) {
    is_closed = true;
    current_top = 0;
    comb[0] = x % MAX_VAL;
    comb[1] = y % MAX_VAL;
    comb[2] = z % MAX_VAL;
    trycomb = { 1, 1, 1 };
    trydir = { 'q', 'q', 'q' };
    rot = { 1,1,1 };
}

0
投票

如前所述,您必须将构造函数更改为

lock::lock(int x, int y, int z) {
    is_closed = true;
    current_top = 0;
    comb[0] = x % MAX_VAL;
    comb[1] = y % MAX_VAL;
    comb[2] = z % MAX_VAL;
    trycomb = { 1, 1, 1 };
    trydir = { 'q', 'q', 'q' };
    rot = { 1,1,1 };
}

否则不会初始化班级成员。

其次,如果要删除队列中的第一个元素并使用pop_front删除队列中的最后一个元素,则应使用pop_back(请参阅deque的documentation)。这使代码更具可读性。

© www.soinside.com 2019 - 2024. All rights reserved.