Vector subscript out of range c как исправить
Перейти к содержимому

Vector subscript out of range c как исправить

  • автор:

Ошибка “vector subscript out of range” в цикле

код[1]При компиляции (1) выдает (2). Что делать? Как бороться?

Отслеживать
16k 9 9 золотых знаков 52 52 серебряных знака 100 100 бронзовых знаков
задан 6 мар 2017 в 16:20
Алексей Завальнюк Алексей Завальнюк
11 1 1 золотой знак 1 1 серебряный знак 1 1 бронзовый знак

2 ответа 2

Сортировка: Сброс на вариант по умолчанию

Вы не можете применять оператор индексирования к вектору, который еще не имеет элементов.

Поэтому вам следует написать перед циклами

cin >> str; cin >> stb; vect.resize(str, std::vector(stb)); 

То есть сначала нужно создать элементы вектора, а затем лишь обращаться к ним по индексу.

Vector subscript out of range c как исправить

I’m trying to initialize a class with a 2D matrix subclass. I’ve been trying to use a double vector (vector< vector> maze_cell) and then access it like a 2d array — I’m new to vectors and I think this may be the source of my problem.

When I debug my program, the runtime error: vector subscript out of range occurs as soon as I attempt to access the first entity of the matrix. From what I’ve researched about this runtime error, it should occur when I try and access an element outside of the memory — how can this occur when:
1) I try and access the [0][0] location.
2: Vectors are supposed to dynamically allocate memory when I need it.

what follows is my code, hopefully commented enough 🙂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
 using namespace std; int main() < string temp; char char_array[100][100]; ifstream fin(infile,ios::app); cout "This is the current maze:" //output the maze stored in the infile adress cout //reset file pointer to the beginning of the file. fin.clear(); int dimention, i, j; getline(fin, temp); // get the first line - this should be the dimention scale. dimention = atoi(temp.c_str()); for(j=0;j<100;j++) < for(i=0;i<100;i++) < char_array[i][j] = 'N'; > > for(j=0;jfor(i=0;i' '); char_array[i][j] = char(temp.c_str());// this appears in my array as 0 - I don't know why //- shouldn't I be taking in the char from the temp string //- it works for dimention > > Maze M(dimention); // this is as far as the compiler gets - this function is in Maze.h M.setmaze(char_array); M.print(); return 0; >

Maze.h — the problem occurs in this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
 using namespace std; class Maze < public: Maze(int dimention_value); void setmaze(char maze_array[100][100]); int setstart(int x_coord, int y_coord); Maze dead_end_fill(); void print(); private: int dimention; vector> maze_cell; // vector of vector of type Cells - each stores a block of the maze. >; Maze::Maze(int dimention_value) //initialisation function < int i,j; dimention = dimention_value; for (i=0;ifor(j=0;j'0'); //***runtime error here*** //set all the cells to 0 (mainly for debugging) maze_cell[i][j].setxy(i,j); //initialise all the coordinate values for each cell. > > > void Maze::setmaze(char maze_array[100][100])// function to shift dimention*dimention chars of the maze_array into the Maze class. < int i,j; for(i=0;ifor(j=0;j > int Maze::setstart (int x_coord, int y_coord) //function to set the start point of the maze. < if(maze_cell[x_coord][y_coord].free()) < maze_cell[x_coord][y_coord].setstate('s'); //set point to s return 1; // return 1 if sucessful > return 0; //return 0 if unsucessful (tried to start in a wall) > void Maze::print() // function to print the maze class < int i, j; for(i=0;ifor(j=0;j cout > 

finally the Cell.h file — I think this is ok 😀 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
 class Cell < public: int get_x() return x;>; int get_y() return y;>; // get_"variable"() -> returns the variable char get_state() return state;>; int wall(); //returns 1 if the block is a wall int free(); //returns 1 if the block is a free space int goal(); //returns 1 if the block is the goal int start();//returns 1 if the block is the start void setx(int x_val) ; void sety(int y_val) ; void setxy(int x_val, int y_val) ; //set"variable"(X) -> variable gets value of X void setstate(char c) ; private: int x,y; // variables char state; >; int Cell::wall() < if(state == 'x') return 1; else return 0; > int Cell::free() < if(state =='p') return 1; else return 0; > int Cell::goal() < if(state =='g') return 1; else return 0; > int Cell::start() < if(state =='s') return 1; else return 0; > 

What is the source of this runtime error?

As you may have noticed above I’m also having trouble getting the characters to put into my initial 100×100 array — they show up as all ‘0’ when I’m expecting Xs and Ps — if anyone has a fix I’d be grateful.

Thanks for any help you can provide — I’ve been tearing my hair out over this.

p.s. first time poster — be gentle!

Ошибка «vector subscript out of range»

Author24 — интернет-сервис помощи студентам

Доброго времени суток,форумчане!При запуске выскакивает ошибка из заголовка. Не понимаю,как исправить.
Сам код:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
#include #include #include using namespace std; int main() { int SIZE, i = 0, a = 0, sum = 0, im = 0, jm = 0, sort; setlocale(LC_ALL, "ru"); srand(time(NULL)); cout  "Введите размер вектора: "  endl; cin >> SIZE; vector int> myVector(SIZE); for (i = 0; i  SIZE; i++) { myVector[i] = -999 + rand() % 1000; cout  myVector[i]  endl; } for (auto elem : myVector) { if (elem  0) { sum += elem; } ++i; } cout  "1. Сумма отрицательных чисел = "  sum  endl; int proizvedenie = 0; int max = myVector[0]; int min = myVector[0]; for (auto elem : myVector) { if (elem > max) { max = elem; im = myVector[i]; } if (elem  min) { min = elem; jm = myVector[i]; } } if (im  jm) { for (int i = jm; i  im; i++) { proizvedenie *= myVector[i]; } } else if (jm > im) { for (int i = jm; i  im; i++) { proizvedenie *= myVector[i]; } } cout  "2. Произведение элементов, расположенных между максимальным и минимальным элементами = "  proizvedenie  endl; for (int i = 0; i  SIZE; i++) { if (myVector[i] > myVector[i + 1]) { sort = myVector[i]; myVector[i] = myVector[i + 1]; myVector[i + 1] = a; } } for (int i = 0; i  SIZE; i++) { cout  "Отсортированный массив : "  endl  myVector[i]  endl; } }

94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:

Ошибка: Vector subscript out of range
Доброго времени суток! Переписывал задачу с джавы на плюсы, но столкнулся с некоторыми непонятными.

Ошибка vector subscript out of range
Есть структура данных бор. Написана библиотека: #include "pch.h" #include <iostream> #include.

Ошибка: Vector subscript out of range
Всю голову сломал, не вижу где ошибка. Выводит только первые 5 итераций, вместо 45. int.

Ошибка vector subscript out of range
Пишет "vector subscript out of range" Смысл этой задачи найти число с максимальной суммой.

C++ : vector subscript out of range?

I’m new to C++ and I’m trying to write a program which opens a file «parameters.txt», which has 8 space-delimited numbers in it. Then I use these numbers in a separate function RK4() to get 3 arrays (y1, y2, t). Then I manipulate these arrays in main() and output a file «output.txt» to the working directory This is my code:

#include #include #include #include #include #include #include #include using namespace std; tuple, vector, vector> RK4() < //open parameters.txt, put data into a vector ifstream fin("parameters.txt"); vectordata; int element; while (fin >> element) < data.push_back(element); >//define tspan vector tspan(2); tspan[0] = 0.0; tspan[1] = data[7]; //define y0 vector y0(4); y0[0] = data[4]; y0[1] = data[5]; y0[2] = 0.0; y0[3] = 0.0; double theta1 = y0[0]; double theta2 = y0[1]; double omega1 = y0[2]; double omega2 = y0[3]; //define stepSize double stepSize; stepSize = data[6]; //define range int range = int(tspan[1] / stepSize); //define other constants double m1, m2, l1, l2; m1 = data[0]; m2 = data[1]; l1 = data[2]; l2 = data[3]; double g = 9.81; //define y, t vectors vector y1(range); vector y2(range); vector y3(range); vector y4(range); vector t(range); for (double i = 0.0; i < 1.0 * range; i++) < t[i] = i * stepSize; >//enter y0 into first value y1[0] = theta1; y2[0] = theta2; y3[0] = omega1; y4[0] = omega2; //loop to find y, t vectors for (int i = 0; i < range - 1; i++) < //finding all k values: //k1 double dTheta1_1 = y3[i]; double dOmega1_1 = (-g * (2 * m1 + m2) * sin(y1[i]) - m2 * g * sin(y1[i] - 2 * y2[i]) - 2 * sin(y1[i] - y2[i]) * m2 * (pow(y4[i], 2) * l2 + pow(y3[i], 2) * l1 * cos(y1[i] - y2[i]))) / (l1 * (2 * m1 + m2 - m2 * cos(2 * y1[i] - 2 * y2[i]))); double dTheta2_1 = y4[i]; double dOmega2_1 = (2 * sin(y1[i] - y2[i]) * (pow(y3[i], 2) * l1 * (m1 + m2) + g * (m1 + m2) * cos(y1[i]) + pow(y4[i], 2) * l2 * m2 * cos(y1[i] - y2[i]))) / (l2 * (2 * m1 + m2 - m2 * cos(2 * y1[i] - 2 * y2[i]))); //k2 double dTheta1_2 = y3[i] + 0.5 * stepSize * dTheta1_1; double dOmega1_2 = (-g * (2 * m1 + m2) * sin(y1[i] + 0.5 * stepSize * dTheta1_1) - m2 * g * sin((y1[i] + 0.5 * stepSize * dTheta1_1) - 2 * (y2[i] + 0.5 * stepSize * dTheta2_1)) - 2 * sin((y1[i] + 0.5 * stepSize * dTheta1_1) - (y2[i] + 0.5 * stepSize * dTheta2_1)) * m2 * (pow(y4[i] + 0.5 * stepSize * dOmega2_1, 2) * l2 + pow(y3[i] + 0.5 * stepSize * dOmega1_1, 2) * l1 * cos((y1[i] + 0.5 * stepSize * dTheta1_1) - (y2[i] + 0.5 * stepSize * dTheta2_1)))) / (l1 * (2 * m1 + m2 - m2 * cos(2 * (y1[i] + 0.5 * stepSize * dTheta1_1) - 2 * (y2[i] + 0.5 * stepSize * dTheta2_1)))); double dTheta2_2 = y4[i] + 0.5 * stepSize * dTheta2_1; double dOmega2_2 = (2 * sin((y1[i] + 0.5 * stepSize * dTheta1_1) - (y2[i] + 0.5 * stepSize * dTheta2_1)) * (pow(y3[i] + 0.5 * stepSize * dOmega1_1, 2) * l1 * (m1 + m2) + g * (m1 + m2) * cos(y1[i] + 0.5 * stepSize * dTheta1_1) + pow(y4[i] + 0.5 * stepSize * dOmega2_1, 2) * l2 * m2 * cos((y1[i] + 0.5 * stepSize * dTheta1_1) - (y2[i] + 0.5 * stepSize * dTheta2_1)))) / (l2 * (2 * m1 + m2 - m2 * cos(2 * (y1[i] + 0.5 * stepSize * dTheta1_1) - 2 * (y2[i] + 0.5 * stepSize * dTheta2_1)))); //k3 double dTheta1_3 = y3[i] + 0.5 * stepSize * dTheta1_2; double dOmega1_3 = (-g * (2 * m1 + m2) * sin(y1[i] + 0.5 * stepSize * dTheta1_2) - m2 * g * sin((y1[i] + 0.5 * stepSize * dTheta1_2) - 2 * (y2[i] + 0.5 * stepSize * dTheta2_2)) - 2 * sin((y1[i] + 0.5 * stepSize * dTheta1_2) - (y2[i] + 0.5 * stepSize * dTheta2_2)) * m2 * (pow(y4[i] + 0.5 * stepSize * dOmega2_2, 2) * l2 + pow(y3[i] + 0.5 * stepSize * dOmega1_2, 2) * l1 * cos((y1[i] + 0.5 * stepSize * dTheta1_2) - (y2[i] + 0.5 * stepSize * dTheta2_2)))) / (l1 * (2 * m1 + m2 - m2 * cos(2 * (y1[i] + 0.5 * stepSize * dTheta1_2) - 2 * (y2[i] + 0.5 * stepSize * dTheta2_2)))); double dTheta2_3 = y4[i] + 0.5 * stepSize * dTheta2_2; double dOmega2_3 = (2 * sin((y1[i] + 0.5 * stepSize * dTheta1_2) - (y2[i] + 0.5 * stepSize * dTheta2_2)) * (pow(y3[i] + 0.5 * stepSize * dOmega1_2, 2) * l1 * (m1 + m2) + g * (m1 + m2) * cos(y1[i] + 0.5 * stepSize * dTheta1_2) + pow(y4[i] + 0.5 * stepSize * dOmega2_2, 2) * l2 * m2 * cos((y1[i] + 0.5 * stepSize * dTheta1_2) - (y2[i] + 0.5 * stepSize * dTheta2_2)))) / (l2 * (2 * m1 + m2 - m2 * cos(2 * (y1[i] + 0.5 * stepSize * dTheta1_2) - 2 * (y2[i] + 0.5 * stepSize * dTheta2_2)))); //k4 double dTheta1_4 = y3[i] + stepSize * dTheta1_3; double dOmega1_4 = (-g * (2 * m1 + m2) * sin(y1[i] + stepSize * dTheta1_3) - m2 * g * sin((y1[i] + stepSize * dTheta1_3) - 2 * (y2[i] + stepSize * dTheta2_3)) - 2 * sin((y1[i] + stepSize * dTheta1_3) - (y2[i] + stepSize * dTheta2_3)) * m2 * (pow(y4[i] + stepSize * dOmega2_3, 2) * l2 + pow(y3[i] + stepSize * dOmega1_3, 2) * l1 * cos((y1[i] + stepSize * dTheta1_3) - (y2[i] + stepSize * dTheta2_3)))) / (l1 * (2 * m1 + m2 - m2 * cos(2 * (y1[i] + stepSize * dTheta1_3) - 2 * (y2[i] + stepSize * dTheta2_3)))); double dTheta2_4 = y4[i] + stepSize * dTheta2_3; double dOmega2_4 = (2 * sin((y1[i] + stepSize * dTheta1_3) - (y2[i] + stepSize * dTheta2_3)) * (pow(y3[i] + stepSize * dOmega1_3, 2) * l1 * (m1 + m2) + g * (m1 + m2) * cos(y1[i] + stepSize * dTheta1_3) + pow(y4[i] + stepSize * dOmega2_3, 2) * l2 * m2 * cos((y1[i] + stepSize * dTheta1_3) - (y2[i] + stepSize * dTheta2_3)))) / (l2 * (2 * m1 + m2 - m2 * cos(2 * (y1[i] + stepSize * dTheta1_3) - 2 * (y2[i] + stepSize * dTheta2_3)))); double theta1New = y1[i] + (stepSize / 6.0) * (dTheta1_1 + 2 * dTheta1_2 + 2 * dTheta1_3 + dTheta1_4); double omega1New = y3[i] + (stepSize / 6.0) * (dOmega1_1 + 2 * dOmega1_2 + 2 * dOmega1_3 + dOmega1_4); double theta2New = y2[i] + (stepSize / 6.0) * (dTheta2_1 + 2 * dTheta2_2 + 2 * dTheta2_3 + dTheta2_4); double omega2New = y4[i] + (stepSize / 6.0) * (dOmega2_1 + 2 * dOmega2_2 + 2 * dOmega2_3 + dOmega2_4); // updating y arrays y1[i + 1] = theta1New; y2[i + 1] = theta2New; y3[i + 1] = omega1New; y4[i + 1] = omega2New; >return make_tuple(y1, y2, t); > int main() < //open parameters.txt, put data into a vector ifstream fin("parameters.txt"); vectordata; int element; while (fin >> element) < data.push_back(element); >//define tspan vector tspan(2); tspan[0] = 0.0; tspan[1] = 10.0; //define stepSize double stepSize; stepSize = data[6]; //define range int const range = 1000; //define other constants double l1 = data[2]; double l2 = data[3]; //get y1, y2, t from RK4 function auto temp = RK4(); vector y1 = get(temp); vector y2 = get(temp); vector t = get(temp); double x_1[range], y_1[range], x_2[range], y_2[range]; //define x_1, x_2, y_1, y_2 for (int i = 0; i < range; i++) < x_1[i] = < sin(y1[i]) * l1 >; y_1[i] = < -cos(y1[i]) * l1 >; x_2[i] = < sin(y1[i]) * l1 + sin(y2[i]) * l2 >; y_2[i] = < -cos(y1[i]) * l1 - cos(y2[i]) * l2 >; > //writing x,y positions at time t to output.txt ofstream myfile; myfile.open("C:\\mydirectory\\output.txt"); if (myfile.is_open()) < myfile cout cout cout cout cout else cout

When I try to build and run the program (in Visual Studio) I get this error:

The thread 0x22c0 has exited with code 0 (0x0). Debug Assertion Failed! Expression: vector subscript out of range For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts. The program has exited with code 3 (0x3).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *