
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Array of Strings According to String Lengths in C++
Here we will see how to sort a list of strings based on their lengths. So if a string has less number of characters, then that will be placed first, then other longer strings will be placed. Suppose the strings are
str_list = {“Hello”, “ABC”, “Programming”, “Length”, “Population”}
after sorting, they will be −
str_list = {“ABC”, “Hello”, “Length”, “Population”, “Programming”}
Here we will create our own comparison logic to sort them. That comparison logic will be used in the sort function in C++ STL.
Algorithm
compare(str1, str2): Begin if length of str1 < length of str2, then return 1 return 0 End
Example
#include<iostream> #include<algorithm> using namespace std; int compare(string str1, string str2){ if(str1.length() < str2.length()) return 1; return 0; } main(){ string str_list[] = {"Hello", "ABC", "Programming", "Length", "Population"}; int n = 5; sort(str_list, str_list + n, compare); for(int i = 0; i<n; i++){ cout << str_list[i] << " "; } }
Output
ABC Hello Length Population Programming
Advertisements