Sort characters of a string in C++
This post will discuss how to sort characters of a string in C++.
The standard and efficient solution to inplace sort characters of a string is using the std::sort algorithm from header <algorithm>. It is usually implemented using the Introsort algorithm, which is a hybrid of quicksort, heapsort, and insertion sort.
The std::sort algorithm accepts an iterator to the initial and final position, and sorts elements in that range in increasing order. A typical invocation of the std::sort algorithm would look like below, to sort a std::string:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> #include <algorithm> int main() { std::string word = "DBCA"; std::sort(word.begin(), word.end()); std::cout << word << std::endl; // ABCD return 0; } |
The above two-arg std::sort overload uses the std::less<>() comparison object, which delegates the call to operator<. We can provide the custom comparison function as the third argument to the std::sort function to define the ordering. For example, to sort the string in descending order, use the std::greater<>() function object, which delegates the call to operator>.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> #include <algorithm> int main() { std::string word = "DBCA"; std::sort(word.begin(), word.end(), std::greater<int>()); std::cout << word << std::endl; // DCBA return 0; } |
Since C++14, we can skip the template arguments to std::greater function object. i.e., std::greater<>() will work.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> #include <algorithm> int main() { std::string word = "DBCA"; std::sort(word.begin(), word.end(), std::greater<>()); std::cout << word << std::endl; // DCBA return 0; } |
To avoid modifications to the original string, consider making a copy of it and then sorting it. The following program demonstrates this by preserving the original string and sorting the copy:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <string> #include <algorithm> int main() { std::string word = "DBCA"; std::string sorted = word; std::sort(sorted.begin(), sorted.end()); std::cout << sorted << std::endl; // ABCD return 0; } |
That’s all about sorting the characters of a string in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)