Segmentation fault

I am a little new to c++ and this is the first time I have encountered this error. I am a lost as to its meaning and how to fix it. I would appreciate it if anyone could point me in the right direction to fixing my problem. Thanks. So what my code should do is that merges two sorted vectors, producing a new sorted vector. Keep an index into each vector, indicating how much of it has been processed already. Each time, append the smallest unprocessed element and advance its index. But when I run my code I receive a message that displaces "Segmentation fault". I have no idea what it means or what exactly is wrong with my code.

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
#include <iostream>
#include <vector>

using namespace std;

vector <int> merge_sorted(vector<int> a, vector<int> b)
{
	int i, j ;
	vector <int> c;
	if (a[i] < b[j]) {
	   c.push_back(a[i]);
	   i++;
	}else{
	   c.push_back(b[j]);
	   j++;
	}

	while (j< b.size()) {
	    c.push_back(b[j]);
	    j++;
	}
	while (i< a.size()) {
	    c.push_back(a[i]);
	    i++;
	}
     
	return c;
}
main()
{
	vector<int> a, b, c;

	int temp;

	cin >> temp;

	while ( temp != -1) {
	   a.push_back(temp);
	   cin >> temp;
	}

	cin >> temp;

	while (!cin.eof()) {
	   b.push_back(temp);
	   cin >> temp;
	}
	c = merge_sorted (a,b);
	
	for (int i = 0; i < c.size(); i++)
	   cout << c[i] << " ";
	cout<<endl;
}

Last edited on
1. Put your code into code tags.
2. Properly indent your code to make it readable

3. In your merge_sorted function, intialize i and j to zero.
4. In the same function, the first 'if...else' clause needs to be executed more than once. Create a loop to contain this code that loops until one of the input vectors is empty.
Last edited on
Topic archived. No new replies allowed.