I am new to C++, so I am trying to understand why the following code does not work:
std::sort(arr, arr + j);
for (int i = 0; i < j; i++) {
cout << arr[i] << "\n";
}
Input I test: a, u, m
Output I expect: a, m, u
But getting still a, u, m
.
I am assuming it is because I put a pointer to the array into the sort()
(that part of the code is in the function)? But I've read so many questions here on how to sort the pointers of the array and really got stuck. Could please somebody explain, in an easy way for a beginner to understand, why my code does not work, and how to fix it?
UPDATE:
struct Phones {
char surname[50];
int yearWhenPhoneRegistred;
int phoneNumber;
};
Phones group[20];
void findDataByYear(struct Phones group[], int year, char *arr[]);
int main {
int year = 0;
char* surnameArr[20] = {};
cout <<"Please, type the year value to apply the sorting: \n";
cin >> year;
findDataByYear(group, year, surnameArr);
return 0;
}
void findDataByYear(struct Phones group[], int year, char *arr[]) {
int j = 0;
for (int i = 0; i < 20; i++) {
if (group[i].yearWhenPhoneRegistred > year) {
arr[j] = group[i].surname;
j++;
}
}
std::sort(arr, arr + j);
printf(" Surname |\n-------------------\n");
for (int i = 0; i < j; i++) {
cout << arr[i] << "\n";
}
}