Use 'sort' with char array (C++)

42,854

Solution 1

Yes. That is definitely possible. You could know that just by writing some sample code, such as this:

char charArray[] = {'A','Z', 'K', 'L' };

size_t arraySize = sizeof(charArray)/sizeof(*charArray);

std::sort(charArray, charArray+arraySize);

//print charArray : it will print all chars in ascending order.

By the way, you should avoid using c-style arrays, and should prefer using std::array or std::vector.

std::array is used when you know the size at compile-time itself, while std::vector is used when you need dynamic array whose size will be known at runtime.

Solution 2

Yes:

char array[] = "zabgqkzg";

std::sort(array, array+sizeof(array));

See http://ideone.com/0TkfDn for a working demo.

Solution 3

The proper way is, of course, to use std::begin() and std::end():

std::sort(std::begin(array), std::end(array));

If you don't have a C++ 2011 compiler, you can implement corresponding begin() and end() functions, e.g.:

template <typename T, int Size>
T* end(T (&array)[Size]) {
    return array + Size;
}
Share:
42,854
Harish Vishwakarma
Author by

Harish Vishwakarma

Updated on July 09, 2022

Comments

  • Harish Vishwakarma
    Harish Vishwakarma almost 2 years

    Is it possible to use std::sort defined inside <algorithm> for sorting char arrays according to their ASCII value? If yes, please provide an example.