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
|
#include <iostream>
#include <string>
class Person{
public:
std::string name;
int age;
void Print();
Person(std::string,int);
int temp;
};
//constructor
Person::Person(std::string keyName, int keyAge){
name=keyName;
age=keyAge;
};
void Person::Print(){
std::cout<<name<<", "<<age<<"\n";
};
int LinearSearch(Person* persArray,int n,int key){
for(int i = 0;i<n;i++){
if(persArray[i].age==key){
return i;
}
}
return -1;
};
//I tried using a pointer like in the search function but that gives errors and I don't understand why
int SortArray(int tempArray[], int n){
for(int i =0 ;i<n;i++){
int nrLeft=n-i;
for(int j = 0 ;j<nrLeft;j++){
if (tempArray[j]<tempArray[j-1]){
int temp = tempArray[j];
tempArray[j]=tempArray[j-1];
tempArray[j-1]=temp;
}
}
}
for(int i=0;i<n;i++){
std::cout<<tempArray[i]<<std::endl;
}
return 0;
};
int main(){
//Print
Person pers("Johan",23);
pers.Print();
//array for searching
Person p[4] {{"karolina",21},{"Chuck Norris",9000},{"Bad Luck Brian",18},{"Johan",23}};
/* This is the array I'd like sorted
Person familj[4] {{"karolina",21},{"Chuck Norris",9000},{"Bad Luck Brian",18},{"Johan",23}};*/
int index=LinearSearch(p,4,23);
if(index==-1){
std::cout<<"person not found";
} else{
std::cout<<p[index].name<<" can be found on index "<<index<<std::endl;
}
//function works but I can't create an array in class Person without errors nor sort string"
int familj[4] {21,9000,18,23};
int sort=SortArray(familj,4);
return 0;
};
|