Попытка чтения строк из файла в вектор без знака - PullRequest
2 голосов
/ 17 января 2020

Я действительно новичок в программировании, так что терпите меня. При запуске следующего кода я всегда получаю фатальную ошибку:

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.

            }
        }

1 Ответ

1 голос
/ 17 января 2020

Чтобы динамически увеличить 2D вектор в l oop, вам нужно добавить новый внутренний вектор, и, учитывая новый внутренний вектор, добавить элементы к нему.

Вот пример:

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