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.
#include<iostream>
#include<string>
usingnamespace 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.