Challenge: Sort by Length

Lab C++ Intermediate 20 points

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
Sample input available Sample output available
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
HOME LABS COMMUNITY DASHBOARD