Deque 迭代器超出范围

deque iterator out of range

本文关键字:范围 迭代器 Deque      更新时间:2023-10-16

我正在尝试通过一些类似数组的对象进行洗牌。我想在前面添加一个值,然后弹出最后一个值。我尝试按照我在其他帖子中看到的建议使用 deque,但我仍然收到错误。有什么想法吗?我是C++新手,虽然我可以尝试围绕此问题编写,但我想知道它在哪里,以便我可以修复它。

我得到一个:无法从视觉工作室寻求超出范围的调试错误。

导致问题的函数:

(我最初使用的是向量(

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);
}

在锁定中:

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'};

感谢您的帮助!

看起来你从来没有在构造函数中初始化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 };
}

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

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_frontpop_back删除队列中的最后一个元素(请参阅 deque 的文档(。这使得代码更具可读性。