矢量超出范围
Vector is out of range
本文关键字:范围 更新时间:2023-10-16
祝所有堆垛工度过美好的一天。我正在Quincy2005中运行我的程序,我有以下错误。"在抛出'std::out_of_range的实例后调用Terminate"what():vector::_M_range_check"
下面是我的代码
int ptextLoc,ctextLoc; //location of the plain/cipher txt
char ctextChar; //cipher text variable
//by default, the location of the plain text is even
bool evenNumberLocBool = true;
ifstream ptextFile;
//open plain text file
ptextFile.open("ptext.txt");
//character by character encryption
while (!ptextFile.eof())
{
//get (next) character from file and store it in a variable ptextChar
char ptextChar = ptextFile.get();
//find the position of the ptextChar in keyvector Vector
ptextLoc = std::find(keyvector.begin(), keyvector.end(), ptextChar) - keyvector.begin();
//if the location of the plain text is even
if ( ((ptextLoc % 2) == 0) || (ptextLoc == 0) )
evenNumberLocBool = true;
else
evenNumberLocBool = false;
//if the location of the plain text is even/odd, find the location of the cipher text
if (evenNumberLocBool)
ctextLoc = ptextLoc + 1;
else
ctextLoc = ptextLoc - 1;
//store the cipher pair in ctextChar variable
ctextChar = keyvector.at(ctextLoc);
cout << ctextChar;
}
ptext.txt的内容ab cd ef
如果第一个字母是位于0位置的"a",则配对密码字母表将是kevector[1]。
最新更新:我找到了造成这个错误的行。ctextChar=keyvector.at(ctextLoc);然而,我不知道为什么这条线路会发生这种情况。我希望有人能指导我。
if (ctextLoc > keyvector.size())
应该是
if (ctextLoc >= keyvector.size())
std::vector
的size()
返回值1 --- N
,其中at()
依赖于值0 --- (N - 1)
。因此,您应该使用:
if (keyvector.size() != 0 && ctextLoc > keyvector.size() - 1)
break;
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 尝试通过多个向量访问变量时,向量下标超出范围
- 错误:未在此范围内声明'reverse'
- 正在将指针转换为范围
- 使用std::transform将一个范围的元素添加到另一个范围中
- 在基于范围的for循环中使用结构化绑定声明
- 如何计算数据类型的范围,例如int
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 在C++中查找范围的长度
- 如何设置一个范围来提取我想要获得的信息
- 并行用于C++17中数组索引范围内的循环
- 为左值和右值的包装器实现C++范围
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 超出范围时使用对象
- 不计算一个范围内的完美数
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 如何访问超出其块范围的对象?
- 矢量下标超出SFML游戏中的范围