Sorting class array

Hello!

I am new to c++ and currently learnig about classes.
I have an exercise where I am to create a class object (array) that has a the values string name and int age.
In the exercise I am to make a method that sorts the elements of the array using bubble sorting. And that's where I am stuck.
I have a method called swap that, if correct, should sort the elements.

When I run the program it crashes, there are no error masseges in my error list.

I have been staring at this quite a while and cannot figure it out.

Thank you in advance for helping me!

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
#include<iostream>
#include<string>
using namespace std;

class Person
{
public:
	string name;
	int age;
	
	Person::Person();

	void setinfo(string a, int b)
	{
		name = a;
		age = b;
	}


	void printout() 
	{
		cout << "The persons name is " << name << " and is " << age << " years old." << endl;
	}


	int linsearch(Person p[], int n, int a) 
	{
		for (int i = 0; i <= n; i++)
		{
			if (p[i].age == a)
				return i;
		}
		return -1;
	}

	void swap(Person &p, Person &q)
	{
		Person temp;
		temp.name = p.name;
		temp.age = p.age;
		p.name = q.name;
		p.age = q.age;
		q.name = temp.name;
		q.age = temp.age;
	}

	void bubblesort(Person p[], int n) 
	{
		int max = n;
		for (int i = 0; i < max; i++)
		{
			int nrleft = max - i;

			for (int j = 0; j < nrleft; j++)
			{
				if (p[j].age > p[j + 1].age)
				{
					Person::swap(p[j], p[j + 1]);
				}
			}
		}
	}
	
	

};

Person::Person()
{

}





int main()
{

	Person family[4];
	for (int i = 0; i < 4; i++)
	{
		string a;
		int b;
		cout << "Enter name and age: " << endl;
		cout << "Name: ";
		cin >> a;
		cout << "age: ";
		cin >> b;

		family[i].setinfo(a, b);
		
	}

	family[4].bubblesort(family, 4); //calling class method


	for (int j = 0; j < 4; j++)
	{
		family[j].printout();
		
	}



	cin.get();
	cin.get();
	return 0;
}
Your bounds-checking for the bubblesort method doesn't work; the first run-through of the outer for loop sets nrleft to max, which is the index of the last element of the array; you then look at p[j+1] in the next for loop which doesn't work when j=nrmax-1; you're now outside of the array, which is invalid and causes a crash.
Of course! Thank you!
Topic archived. No new replies allowed.