C++ Sorting algorithm error

Hi,

Hoping someone can point out the error of my ways.
Im doing an assignment in class where we have to create a c++ program that uses a sorting algorithm to sort a series of character lines in a CSV file.

I've got it all set up, but im getting an error:
Expression: vector subscript out of range.

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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <chrono>

using namespace std;
using namespace chrono;


void swap(string& xp, string& yp)//used to swap things
{
	string temp = xp;
	xp = yp;
	yp = temp;
}


void bubbleSortaTOz(vector<string>& vec)
{
	int i, j;

	for (i = 0; i < vec.size() - 1; i++)
	{
		for (j = 0; j < vec.size() - i - 1; j++)
		{
			if (vec[j].compare(vec[j + 1]) > 0)
			{ 
				swap(vec[j], vec[j + 1]);
			}
		}
	}
}


void bubbleSortzTOa(vector<string>& vec)
{
	int i, j;
	for (i = 0; i < vec.size() - 1; i++)
	{
		for (j = 0; j < vec.size() - i - 1; j++)
		{
			if (vec[j].compare(vec[j + 1]) < 0) 
			{ 
				swap(vec[j], vec[j + 1]);
			}
		}

	}
}

int main()
{
	int count = 1, time;
	microseconds duration;


	vector<int>endVector;
	vector<string>
		mainVector, 
		aTOz, 
		zTOa,
		randomVector; 

	ifstream inputFile;
	ofstream outputFile;
	inputFile.open("Data.csv");
	outputFile.open("EndData.csv"); 
	string line;


	while (inputFile.good()) {
		getline(inputFile, line, '\n');
		mainVector.push_back(line);
	}
	inputFile.close();

	for (int i = 10; i <= 3000; i *= 1.5) {
		cout << "Iteration: " << count << " out of 15" << endl;
		endVector.push_back(i);
		
		for (int j = 0; j <= i; j++) {
			aTOz.push_back(mainVector[j]); /*--------------------------- Apparently the error is here 'An invalid 
parameter was passed to a function that considers invalid paramters fatal -- but when launched, it gives error of 
- Expression: vector subscript out of range.*/
			zTOa.push_back(mainVector[j]);
			randomVector.push_back(mainVector[j]);
		}

		bubbleSortaTOz(aTOz); //sorts the data
		bubbleSortzTOa(zTOa);


		auto start = high_resolution_clock::now();
		bubbleSortaTOz(aTOz);
		auto stop = high_resolution_clock::now();

		duration = duration_cast<microseconds>(stop - start);
		time = duration.count();
		endVector.push_back(time);

		start = high_resolution_clock::now();
		bubbleSortaTOz(zTOa);
		stop = high_resolution_clock::now();

		duration = duration_cast<microseconds>(stop - start);
		time = duration.count();
		endVector.push_back(time);


		start = high_resolution_clock::now();
		bubbleSortaTOz(randomVector);
		stop = high_resolution_clock::now();

		duration = duration_cast<microseconds>(stop - start);
		time = duration.count();
		endVector.push_back(time);


		aTOz.clear();
		zTOa.clear();
		randomVector.clear();

		count++;
	}

	count = 0;

	for (int i = 0; i < endVector.size(); i += 4) {
		if (count == 0) {
			outputFile << "Data" << "," << "'Fastest Time'" << "," << "'Slowest time'" << "," << "'Average time'" << endl;
			count = 1;
		}
		outputFile << endVector[i] << "," << endVector[i + 1] << "," << endVector[i + 2] << "," << endVector[i + 3] << endl;
	}

	outputFile.close();
	return 0;
}


Apologies for the length of code, but thought it would be best to post the whole thing in case there might be glaring mistakes that Im making?

Any advice would be appreciated.

Thank you

P.s. The input data basically looks like this:
KQLNWTIGXNFWEXBWAYC
TXWBARLEXNZMKHTOFCJ
ABOPEOMJKJPBQRNOQKN
BCXADQMDPWDMQLMDAIE
ZSZWRIJXEPYYKACQVEZ
---Continued for 3000 rows---
Last edited on
Look at this snippet: for (int i = 10; i <= 3000; i *= 1.5) {, are you sure your vector has 3001 entries? Remember that things like arrays, strings, and vectors start at zero and stop at "size" minus 1, which means that using <= is usually a mistake.

By the way do you realize that vectors know their sizes? Instead of the magic number (3000) have you considered letting the vector tell you it's size?

Lastly for not using good() to control an input loop is usually incorrect, you should use the actual read instead.


What are you trying to do in the loop on line 78? j is likely out of bounds.
@jlb yep, I think you are right.
I changed it to use the vector size, rather than a number.

But now, the issue appears to be that the program is not reading in the data from the file at all (I think this was the issue to begin with as well) - the program simply runs, and exits as though its done it.

I dont see any issue with how I read in the data - or put the data in a vector... or am I missing something?
@code777 that line is to iterate over the data 15 times - each time taking more data to 'sort' and then Im able to measure the time it takes for the sorting algorithm to do its job based on the size of data

And yes, I think it is out of bounds - but the bounds are 0 from what I can tell.
The issue is as above - its not reading in the data properly for whatever reason
yes, the .good() thing is a noob-trap. Don't do that. .eof() is also a noob-trap. Neither one do what a new programmer expects them to do in the way they want to do it. There are ways to use these tools to do what you want, but its awkward because you don't need them for this. It does not help that there are (bad) examples that use them across the web.

use
while( getline(inputFile, line) ) // \n is the default, don't need to put it in.
...push back..

you can also check that your file opened; windows / visual specifically is notorious for changing the folder it is searching for the file in predictable but clunky ways that depend on how you ran the program (its different running from the IDE vs dbl click program and debug vs release vs other are different from each other too).
Last edited on
Silly question - how would I check if it did open the file?
how would I check if it did open the file?

With std::fstream::is_open. Before you try reading from/writing to the file.

http://www.cplusplus.com/reference/fstream/fstream/is_open/
1
2
3
4
5
6
while (getline(inputFile, line)) {
   // do stuff
}
if (!inputFile.eof()) {
   // Some premature error occurred.
}

Yep, as you guys suspected, its not opening the file.
Did the test.

Could there be anything that is causing it not to open it?
i.e. in this part:
1
2
3
4
5
	ifstream inputFile;
	ofstream outputFile;
	inputFile.open("Data.csv");
	outputFile.open("EndData.csv"); 
	string line;


I've changed the inputFile to the full location of the file - and still nothing
It does create the EndData.csv file though.
are you on a cased filesystem like unix? If so, make sure the name and path of the file are all exact matching, no mis-cases.

try printing the file path and name you tried to open from the code. If you are on windows and used window's style paths, did you remember to use \\ escape sequences?

does your program HAVE ACCESS to the folder / file in question?

Is the file open in something like excel, that could lock it from other programs using it?

that is the top contenders for this kind of issue, assuming you checked typos already.
Last edited on
i.e. in this part:

There doesn't seem to be anything absolutely wrong with that code, however you really should start using RAII techniques,

1
2
3
4
5
6
7
std::ifstream inputFile("Data.csv");  // Prefer to use the constructor over the assignment operator.
// And then always, Always check that the file correctly opened:
if(!inputFile)
{
    std::cerr << "Input file failed to open\n";
    return 1;
}


You are sure that "Data.csv" exists as shown, remember some Operating Systems are case sensitive.

This is embarrasing..
I had the input file named Data.csv
But the system recognised iti as Data.csv.csv and wouldnt open in...

It is working great now.

Thank you for the help all!
that tells me most likely you have left default 'hide extensions' setting on in windows. I would suggest to turn that off, it is nothing but trouble to advanced users and programmers.

Most of us have done a few things like this --- stuff happens.
Last edited on
system recognised iti as Data.csv.csv

Looks like a Windows "problem," hiding known extensions.
Topic archived. No new replies allowed.