如何解决从100减小到0时矢量下标超出范围
我调试了此错误,并且我不明白为何此向量下标超出范围。我也查看了此链接,但无济于事:
Vector subscript out of range
我有一个名为board
的类,带有一个私有数据成员vector<int> m_Board_board
。在board
构造函数中,我将这个变量从1
初始化为100
,并使用friend 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 = 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
他们都在做相同的事情,但是其中一个将 vector订阅抛出范围错误,而另一个则工作正常。现在,在我收到必须使用迭代器的评论之前,我尝试了使用迭代器,并且发生了相同的事情,这促使我尝试使用普通的整数循环来确定问题是否出在使用迭代器上。但是,这不是迭代器,这很奇怪!
但是,在第一种情况下,当我从99
迭代到0
时,它可以正常工作,但不会打印第一个元素(显然!)。
那么,当我开始从100
减小到0
时为什么会超出范围?
解决方法
他们做的不一样!
您的m_Board_board
中包含100个元素,这意味着索引从0,1,2,...,99
开始,在循环的第一个代码中
for (int i = 100; i > 0; --i) {
您正在启动索引100
。这试图访问向量std::vector::operator[]
相对于access out of bounds undefined behaviour的向量中不存在的元素。那是有可能发生的。就您而言,您的程序崩溃了。
您应该从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;
}
这里是a working demo。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。