Challenge: Sort by Length
Completed
Read n words. Sort them by length (shortest first); words of the same length go in alphabetical order. Use sort with a lambda. Print one word per line.
Input
n, then n words.
Output
The sorted words, one per line.
Example
Input
5 pear fig banana kiwi apple
Output
fig kiwi pear apple banana
Editor
C++
Hints
The lambda gets two words and returns true if the first should come first.
If the lengths differ, compare lengths. Otherwise compare the words with <.
Solution explanation
The lambda first compares lengths and only falls back to alphabetical order when they are equal.
Show solution
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
vector<string> words(n);
for (string& w : words) cin >> w;
sort(words.begin(), words.end(), [](const string& a, const string& b) {
if (a.length() != b.length()) {
return a.length() < b.length();
}
return a < b;
});
for (const string& w : words) {
cout << w << "\n";
}
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module