8

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.

1
  • what you want is basically an "alphabetically sorted array" the ASCII value is use for the "standard" way of ordering chars in C and C++, for example a is < than b because of its own ASCII value. Commented Jan 1, 2013 at 15:59

5 Answers 5

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, would it work in the same work for string as well? And can you also take a look at my other question, here stackoverflow.com/questions/14078889/…
Instead of sizeof(charArray)/sizeof(*charArray) you can just use std::size(charArray).
6

Yes:

char array[] = "zabgqkzg";

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

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

2 Comments

Can you also take a look at my other problem? Here, stackoverflow.com/questions/14078889/…
Size -1 or You will sort with the null. std::sort(array, array+sizeof(array)-1);
4

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;
}

3 Comments

Thanks. So begin and end are defined in C++ 2011 compiler and not before that?
Yes (although they are part of the library; I thing they are declared in <iterator>). However, they are easy to define.
K. Please take a look to an another question by me,here stackoverflow.com/questions/14078889/…
0

Answers using sizeof(charArray) assume that the array must be completely filled. When ran using partially filled array, they produce garbage results.

In that case use:

sort(str, str + strlen(str));

Comments

0

I just use this and answered for me.

char name[9] = "zxcda";
int length = 0;
for(int i=0;name[i]!='\0';i++)
    length++;
sort(name , name+length);
cout << name;

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.