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.
-
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.user1824407– user18244072013-01-01 15:59:00 +00:00Commented Jan 1, 2013 at 15:59
5 Answers
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.
2 Comments
sizeof(charArray)/sizeof(*charArray) you can just use std::size(charArray).Yes:
char array[] = "zabgqkzg";
std::sort(array, array+sizeof(array));
See http://ideone.com/0TkfDn for a working demo.
2 Comments
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
<iterator>). However, they are easy to define.