Ariel Yael
Ariel Yael

Reputation: 373

Sorting array of strings in cpp using std:sort

I am trying to sort arrays (yes, not vectors) of strings, following some suggestions from sites such as this one. This is the code I wrote so far, but it always prints out this long error (which has no results on google). How can this be fixed?

#include <algorithm>
#include <cstring>
#include <iostream>
//qsort(names, n, 15, (int (*)(const void *, const void *))strcmp);



int main()
{
    std::cout << "hi";
    char arr[3][6];
    strcpy(arr[0], "hello"), strcpy(arr[1], "hillo"), strcpy(arr[2], "hallo");
    std::sort(arr, arr + 3, [](char const *lhs,
                           char const *rhs) { return strcmp(lhs, rhs) < 0; });
    //qsort(arr, 3, 20, (int (*)(const void *, const void *))strcmp);
    for (int i = 0; i < 3; ++i)
        std::cout << arr[i] << '\n';
}

Upvotes: 1

Views: 703

Answers (2)

Pavan Kumar R
Pavan Kumar R

Reputation: 1

You cannot sort array of arrays using sort inbuilt function. You can traverse through the array of strings and sort each string(str) using sort(str.begin(), str.end()).

Upvotes: 0

eerorika
eerorika

Reputation: 238311

This is the relevant part of the error message:

error: array must be initialized with a brace-enclosed initializer

Which is not very clear unfortunately, but ot comes from within the sorting implementation. So, let us revise the preconditions of the algorithm:

std::sort is implemented by swapping elements. As such, it requires that the elements are swappable. The elements of your array are arrays. Arrays are not swappable. Therefore an array of arrays is not sortable.

will using the type "string" work here?

Using std::string will work. It is swappable. You won't even need a custom comparison function because it is even comparable.

what makes arrays unswappable and other types swappable

Swap is inplemented by move initialisation (and assignment). Language rules say that array is not move initialisable (nor is it assignable). Knowing this, see if the error messsge makes some sense.

Upvotes: 1

Related Questions