- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort an array of strings in ascending order with each string sorted in descending order
In this article, we dive into a unique and interesting problem related to arrays and string manipulation in C++. The problem at hand is "Sort an array of strings in ascending order with each string sorted in descending order". This problem is an excellent way to enhance your knowledge of string manipulation, arrays, and sorting algorithms.
Problem Statement
Given an array of strings, the task is to sort the array in ascending order, but with each string sorted in descending order.
C++ Solution Approach
We can solve this problem by using the sort function provided by the C++ Standard Library. First, we'll sort each individual string in descending order. After that, we'll sort the entire array of strings in ascending order.
Example
Here's the C++ code that implements this solution −
#include <iostream> #include <vector> #include <algorithm> #include <string> using namespace std; void sortArray(vector<string>& arr) { for(string& str : arr) { sort(str.begin(), str.end(), greater<char>()); } sort(arr.begin(), arr.end()); } int main() { vector<string> arr = {"acb", "bca", "abc"}; sortArray(arr); cout << "The sorted array is: "; for(const string& str : arr) { cout << str << " "; } cout << endl; return 0; }
Output
The sorted array is: cba cba cba
Explanation with a Test Case
Let's consider the array of strings {"acb", "bca", "abc"}.
When we pass this array to the sortArray function, it first sorts each string in descending order. The array becomes {"cba", "cba", "cba"}.
Then it sorts the array of strings in ascending order. However, since all the strings are the same, the sorted array remains {"cba", "cba", "cba"}.
Conclusion
This problem presents a unique use case of the sort function from the C++ Standard Library. It's an excellent problem to practice your C++ coding skills and to understand how to sort strings and arrays.