Start learning free

LESSON 388 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: sort v1 — Ascending Alphabetical Sort in C++

Practice

Build a tiny version of the Unix sort command. Given a list of lines, return them sorted in ascending order by character code (like LC_ALL=C sort: uppercase letters come before lowercase ones, "Zebra" before "apple", and an empty line comes first), joined by newline characters (\n). Duplicates are all kept. If the list is empty, return the empty string.

Function signature:

string sortLines(vector<string> lines)

Example:

Input: lines = ["banana", "apple", "cherry"]

Output: "apple\nbanana\ncherry"

When printed:
apple
banana
cherry

Copy the input vector, call std::sort on it (default ascending, which compares by character code), then concat the results into a single string with "\n" separators.

The full solution:
class Solution {
public:
    string sortLines(vector<string> lines) {
        vector<string> sortedLines = lines;
        sort(sortedLines.begin(), sortedLines.end());
        string result;
        for (int i = 0; i < sortedLines.size(); i++) {
            if (i > 0) result += "\n";
            result += sortedLines[i];
        }
        return result;
    }
};

STEP 1 OF 7
    Ctrl + Enter to check

    Sort V1 in C++

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free