【问题标题】:Trying to read strings from a file into an unsigned char vector尝试将文件中的字符串读入无符号字符向量
【发布时间】: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 作为样本大小,但实际文件要大得多,这应该不是问题。向量应该动态增长对吗?编辑:对图片感到抱歉
  • @m0xpl0x 当使用 push_back 之类的某些方法时,向量会动态增长,而不是 operator[] 之类的方法。我建议你看看docs
  • 请注意,您可以使用矢量的sized constructor 为您的元素预先分配空间。甚至更好,因为您使用的是 5x5 的恒定大小,您可以改用 std::array,其大小在编译时是固定的。
  • 向量应该动态增长吧?。致电push_backresizeinsert。使用 [ ] 不会使向量增长。 -- 它用于访问预先存在的元素。

标签: c++ vector char


【解决方案1】:

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

这是一个例子:

#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);    
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多