Debug assertion failed! vector subscript out of range

Hi everyone, I new to C++ and seeking for some advice from c++ experts here. I got the following error. I don't know how to fix it. Hoping someone here can assist me. Thank you for the help.

Debug assertion failed!
Expression: vector subscript out of range.

I have data from text file (2 columns, 10 rows) as below:
44 245.073
56 206.798
100 222.541
70 206.798
65 206.879
85 219.329
96 184.308
57 202.072
37 206.798
14 206.95

I need to read the data from text file and I need to store each column into vector. First column refer to startNode and second column is objFunction.


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
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;

void input()
{
	// Read data from text file
	ifstream sol_IS_route("mydata.txt");
	vector<vector<double>> sol_initial_route;

	for (string line; getline(sol_IS_route, line); )
	{
		sol_initial_route.push_back(vector<double>());
		istringstream iss(line);
		for (double m; iss >> m; )
			sol_initial_route.back().push_back(m);
	}

	vector<double> startNode;
	//assign random start node into array
	for (size_t i = 0; i < sol_initial_route.size(); i++)
	{
		startNode[i] = sol_initial_route[i][0];
		cout << "startNode[" << i << "] = " << startNode[i] << endl;
	}

	vector<double> objFunction;
	//assign objective function for each selected start node into array
	for (size_t i = 0; i < sol_initial_route.size(); i++)
	{
		objFunction[i] = sol_initial_route[i][1];
		cout << "objFunction[" << i << "] = " << objFunction[i] << endl;
	}
}

int main()
{
	input();
}
You haven't given either startNode or objFunction any size ... so their sizes will default to zero. Consequently startNode[i] and objFunction[i] are wrong.
So on line 26/33 you need to use push_back(....) as you did in the previous loop.

Plus it is a good idea to check whether element 0/1 exists in sol_initial_route[i].
Topic archived. No new replies allowed.