0

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.

Code in Studio

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";
    }
}
15
  • Show a minimal reproducible example please. Paste the code as text, no links, no images. Commented Aug 29, 2021 at 17:46
  • Please share a minimal reproducible example. It works when I try it. Commented Aug 29, 2021 at 17:47
  • @ThomasMatthews, added! Commented Aug 29, 2021 at 17:50
  • @FrançoisAndrieux added! Commented Aug 29, 2021 at 17:50
  • FYI, you don't need to use struct when declaring parameters, variables, members or return types. Commented Aug 29, 2021 at 17:56

1 Answer 1

3

The basic problem is that, contrary to the title of your question, you're not trying to sort a char[] array (an array of characters), you're trying to sort a char*[] array (an array of pointers). So, the default sorter (what you get if you use std::sort() without a third functor argument) will just compare the pointers themselves and sort them in memory order, without regard to the characters they are pointing at.

If you want to sort in lexical order, you need to compare the strings:

std::sort(arr, arr+j, [](char *a, char *b)->bool { return strcmp(a, b) < 0; });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.