尝试将字符串从文件读取到无符号字符向量中

Trying to read strings from a file into an unsigned char vector

本文关键字:无符号 字符 向量 读取 文件 字符串      更新时间:2023-10-16

我真的是编码新手,所以请耐心等待。 运行以下代码时,我总是收到致命错误:

Debug Assertion Failed!
Program: [program name]
File: [MS VS path]includevector
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.
}
}

要在循环中动态增长 2D 向量,您需要添加新的内部向量,并给定新的内部向量,向其添加项目。

下面是一个示例:

#include <vector>
int main()
{
std::vector<std::vector<unsigned char>> vectorname;
for (unsigned int i = 0; i < 5; i++) 
{
// add a new vector to the outer std::vector
vectorname.push_back(vector<unsigned char>());
// now add data to the newly added vector. The `back()` returns
// a reference to the last added vector
for (unsigned int j = 0; j < 5; j++) {
vectorname.back().push_back(j);    
}
}