Start learning free

LESSON 24 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V4 in C++: Sort by Column with stable_sort and getline

Practice Read the full explanation

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

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Sort V4 in C++, explained

    Problem overview

    Version 4 of the sort tool adds -k, sorting by a column. Each line is comma-separated and has at least field fields; a field may be empty, as in "a,,c". The function sortLines(vector<string> lines, int field) sorts the lines by the value in the 1-indexed column field, compared as strings by character code, and returns the original lines joined with \n. Lines with equal keys keep their input order. An empty vector gives "".

    With field = 2 and {"alice,30", "bob,25", "carol,40"} the keys are "30", "25" and "40". Ordered by key the lines are bob, alice, carol, so the result is "bob,25\nalice,30\ncarol,40".

    Approach

    This version has two parts. A helper, extractField, pulls out one column of one line. The sort then compares lines by their keys, using a lambda that calls the helper on both lines.

    The sort must be stable, because many lines can share a key. In {"b,x", "a,x", "c,w"} sorted by field 2, the two lines with key "x" must stay in the order b, a. stable_sort guarantees that and sort does not.

    The key is a string, so the comparison is the ordinary string comparison by character code. That means numbers in a column are ordered as text: with field 2, {"x,10", "y,9"} stays as it is, because "10" is smaller than "9" as text.

    The helper could split the whole line into a vector. Reading only as many pieces as needed is shorter, and the lesson does exactly that with a stringstream.

    Step by step

    The lesson first writes the helper, then the sort.

    1. Make a stringstream named ss over line. It lets you read the text piece by piece, the way cin reads input.
    2. Declare a string named token to receive each piece.
    3. Loop field times, with i from 0 while i < field. Reading exactly that many pieces leaves the wanted one in token.
    4. Read with getline(ss, token, ',') inside the loop. The third argument makes the comma the delimiter, instead of the newline: getline reads up to the next comma and discards it.
    5. Return token after the loop.
    6. In sortLines, copy lines into sortedLines.
    7. Call stable_sort with a lambda that captures field. The lambda takes two const string& parameters and returns whether the key of a is smaller than the key of b, each found with extractField.
    8. Create an empty result.
    9. Loop over the positions of sortedLines.
    10. Open an if for i > 0.
    11. Add a newline inside it.
    12. Append sortedLines[i] after the if.
    13. Return result.

    The solution in C++

    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;
        }
    };
    

    The details that matter:

    • Capture field. The lambda's [field] copies the value into the lambda. Without it, the body could not use field and the code would not compile. The helper is a static member, so the lambda can call it without an object.
    • getline with a delimiter. getline(ss, token, ',') replaces the contents of token each time. An empty field gives an empty token, so extractField("a,,c", 2) is "". A trailing empty field works too: extractField("a,b,", 3) is "".
    • The key is the field only. Two lines with equal keys compare as equal even if the rest of the line differs, and stable_sort keeps them in input order. That matches the real command's -s option.
    • Passing by const reference. Both the helper and the lambda take const string&, so no line is copied for each comparison.
    • Too few fields. The lesson guarantees enough fields. With fewer, the loop's last successful read stays in token: extractField("a,b", 3) returns "b", which is a wrong answer and not an error.

    Complexity

    Each comparison parses up to field pieces of two lines, so it costs time proportional to the length of the lines. A stable sort of n lines does O(n log n) comparisons when it can allocate a buffer, and the result is built in one pass. The work is therefore about O(n log n) times the line length. Extra space is the sorted copy, the result string and the sort's buffer.

    Edge cases and common mistakes

    • The column is 1-indexed. With field 1 the key is the part before the first comma: {"alice,30", "bob,25", "carol,40"} comes out as "alice,30\nbob,25\ncarol,40".
    • Ties. {"b,x", "a,x", "c,w"} sorted by field 2 gives "c,w\nb,x\na,x": the w line first, then the two x lines in their original order.
    • Empty fields. An empty key sorts before every non-empty one. {"a,,c", "b,a,c"} by field 2 stays in the same order, because "" is smaller than "a".
    • Numbers in a column. Keys are compared as text, so {"x,10", "y,9"} by field 2 gives "x,10\ny,9".
    • Using sort instead of stable_sort. It may reorder lines with equal keys, which fails the tie cases.
    • Counting the pieces. The loop reads exactly field pieces, so field 2 means two reads and the second piece is what remains in token. Counting from 0 and stopping before field is what makes the 1-indexed column number work directly.
    • Empty input. sortLines({}, 1) returns "".

    Testing

    linesfieldresult
    {"alice,30", "bob,25", "carol,40"}2"bob,25\nalice,30\ncarol,40"
    {"alice,30", "bob,25", "carol,40"}1"alice,30\nbob,25\ncarol,40"
    {"b,x", "a,x", "c,w"}2"c,w\nb,x\na,x"
    {"a,,c", "b,a,c"}2"a,,c\nb,a,c"
    {"x,10", "y,9"}2"x,10\ny,9"
    {}1""
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free