C++ Online Compiler
Example: Sort String Descending with std::greater in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sort String Descending with std::greater #include <iostream> #include <string> // Required for std::string #include <algorithm> // Required for std::sort #include <functional> // Required for std::greater using namespace std; int main() { // Step 1: Initialize the string string myString = "hello_world"; cout << "Original string: " << myString << endl; // Step 2: Sort the string in descending order using std::greater<char>() // std::greater<char>() is a function object that defines a 'greater than' comparison. // std::sort uses this comparator to place larger characters before smaller ones. std::sort(myString.begin(), myString.end(), std::greater<char>()); // Step 3: Print the sorted string cout << "Sorted string (descending): " << myString << endl; return 0; }
Output
Clear
ADVERTISEMENTS