【发布时间】:2020-01-17 18:26:56
【问题描述】:
我对编码还很陌生,所以请耐心等待。 运行以下代码时,总是遇到致命错误:
Debug Assertion Failed!
Program: [program name]
File: [MS VS path]\include\vector
Line: 1502
Expression: vector subscript out of range
这可能是什么原因造成的?
string temp1;
stringstream temp2;
unsigned char temp3;
vector<vector<unsigned char>>vectorname;
for (unsigned int i = 0; i < 5; i++) {
for (unsigned int j = 0; j < 5; j++) {
Datei >> temp1; // copies file into string
temp2 << temp1; //copies string into streamstring
temp2 >> temp3; //copies streamstring into unsigned char
vectorname[i][j] = temp3 //sets the unigned char as value at the i,j, position.
}
}
【问题讨论】:
-
Bild[i][j] = temp3 //sets the unigned char as value at the i,j, position.如消息所示超出范围。错误消息应该是文本而不是图像。 -
是的。但是为什么会超出范围。我使用 5x5 作为样本大小,但实际文件要大得多,这应该不是问题。向量应该动态增长对吗?编辑:对图片感到抱歉
-
请注意,您可以使用矢量的sized constructor 为您的元素预先分配空间。甚至更好,因为您使用的是 5x5 的恒定大小,您可以改用
std::array,其大小在编译时是固定的。 -
向量应该动态增长吧?。致电
push_back、resize或insert。使用[ ]不会使向量增长。 -- 它用于访问预先存在的元素。