Start learning free

LESSON 391 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: sort v4 — Sort by Key Column in C++

Practice

Build the next version of the Unix sort command, this time with the -k flag baked in. Each input line is comma-separated and is guaranteed to have at least field fields (a field may be empty, as in "a,,c"). Given a 1-indexed field number, sort the lines stably by the value at that field, compared as strings by character code, and return the original lines joined by newlines (\n). Lines whose fields are equal keep their original relative order. This matches the real command sort -t, -k N,N -s in the C locale. If the list is empty, return the empty string.

Function signature:

string sortLines(vector<string> lines, int field)

Example:

Input: field = 2, lines = ["alice,30", "bob,25", "carol,40"]

Output: "bob,25\nalice,30\ncarol,40"

When printed:
bob,25
alice,30
carol,40

Use std::stable_sort (NOT plain std::sort, which isn't guaranteed stable). Write a helper that extracts the field via getline on a stringstream, then compare keys in the comparator.

static string extractField(const string& line, int field) {
    stringstream ss(line);
    string token;
    for (int i = 0; i < field; i++) {
        getline(ss, token, ',');
    }
    return token;
}


The full solution:
class Solution {
public:
    static string extractField(const string& line, int field) {
        stringstream ss(line);
        string token;
        for (int i = 0; i < field; i++) {
            getline(ss, token, ',');
        }
        return token;
    }
    string sortLines(vector<string> lines, int field) {
        vector<string> sortedLines = lines;
        stable_sort(sortedLines.begin(), sortedLines.end(), [field](const string& a, const string& b) {
            return extractField(a, field) < extractField(b, field);
        });
        string result;
        for (int i = 0; i < sortedLines.size(); i++) {
            if (i > 0) result += "\n";
            result += sortedLines[i];
        }
        return result;
    }
};

STEP 1 OF 13
    Ctrl + Enter to check

    Sort V4 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