c++ - 从 100 递减到 0 时向量下标超出范围
问题描述
我调试了这个错误,我不明白为什么这个向量下标超出范围。我也看过这个链接,但没有用:
Vector subscript out of range
我有一个board
用私有数据成员调用的类vector<int> m_Board_board
。在board
构造函数中,我将这个变量从1
to初始化,100
并使用friend operator <<
函数从 last 到 end 打印,如下所示:
#ifndef BOARD_H
#define BOARD_H
#include <iostream>
#include <vector>
using std::vector;
using std::ostream;
class Board
{
private:
vector<int> m_Board_board;
public:
Board()
{
for (int i = 1; i < 101; ++i) {
m_Board_board.push_back(i);
}
}
friend ostream& operator << (ostream& os, Board board)
{
for (int i = 100; i > 0; --i) {
os << board.m_Board_board[i] << '\n';
}
return os;
}
};
#endif // !BOARD_H
在我的main
功能中,我正在打印电路板。
#include "Board.h"
using std::cout;
int main()
{
Board board;
cout << board;
system("pause");
}
这会产生以下错误:https ://i.stack.imgur.com/TWVQF.png
现在奇怪的是,如果我将operator <<
功能更改为从头到尾打印,它会按预期工作!
#ifndef BOARD_H
#define BOARD_H
#include <iostream>
#include <vector>
using std::vector;
using std::ostream;
class Board
{
private:
vector<int> m_Board_board;
public:
Board()
{
for (int i = 1; i < 101; ++i) {
m_Board_board.push_back(i);
}
}
friend ostream& operator << (ostream& os, Board board)
{
for (int i = 0; i < 100; ++i) {
os << board.m_Board_board[i] << '\n';
}
return os;
}
};
#endif // !BOARD_H
他们都在做同样的事情,但一个是 throwing vector subscription out of range error,而另一个工作正常。现在,在我收到评论说我必须使用迭代器之前,我用迭代器尝试了它们并且发生了同样的事情,这导致我尝试使用正常的整数循环来确定问题是否与使用迭代器有关。但是,这不是迭代器,而是很奇怪!
但是,在第一种情况下,当我从99
to迭代时0
,它可以完美运行,但不会打印第一个元素(显然!)。
那么,当我开始从100
下降到时,为什么它会超出范围0
?
解决方案
他们没有做同样的事情!
你m_Board_board
有 100 个元素,这意味着索引从0, 1, 2,..., 99
第一个代码开始,在循环中
for (int i = 100; i > 0; --i) {
您正在启动索引100
。这是试图访问向量 vis 中不存在的元素std::vector::operator[]
,即访问越界未定义行为。那就是任何事情都可能发生。在您的情况下,您遇到了程序崩溃。
你应该从开始99
有定义的行为
friend ostream& operator << (ostream& os, Board const& board) /* noexcept */
// ^^^^^^^--> also pass the object by const-ref
{
for (int i = 99; i >= 0; --i) {
os << board.m_Board_board[i] << '\n';
}
return os;
}
或者在反向迭代器的帮助下做
#include <algorithm> // std::copy
#include <iterator>
friend ostream& operator << (ostream& os, Board const& board) /* noexcept */
// ^^^^^^^--> also pass the object by const-ref
{
std::copy(board.m_Board_board.crbegin(), board.m_Board_board.crend(),
std::ostream_iterator<int>(os, "\n"));
return os;
}
这是一个工作演示。
推荐阅读
- c# - 通过字符串转换反序列化枚举时,如何获得空值而不是序列化错误?
- typescript - 按顺序在可观察对象中执行
- python - Pandas 中的 .dropna() 问题
- ruby-on-rails - 在不知道文件名的情况下在 rails 公共目录中派生文件的自动化方法
- c# - 如何在 Web 浏览器控件中单击单独的网页元素
- mysql - 如何为 Spring 和 MySql 设置 Kubernetes
- postgresql - 将 postgres 分区添加到现有表
- ffmpeg - 使用 NVENC 的 FFmpeg GPU 10 位 HEVC 编码
- javascript - 当用户错误地将完整的电子邮件地址包含为用户名时,想要从输入中删除“@email.com”
- azure - 使用用户名和密码写入 Azure Blob