Start learning free

LESSON 23 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V3 in C++: Numeric Order with stable_sort and stoi

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -n flag baked in. Each input line is the string form of an integer that fits in 32 bits (an optional leading -, no leading +; leading zeros such as "007" are allowed). Sort the lines numerically (not lexicographically) in ascending order, and return the original strings joined by newlines (\n). Lines with the same numeric value keep their original relative order (a stable sort). The real sort -n would break such ties by comparing the text; this version does not. If the list is empty, return the empty string.

Note: lexicographic sort would put "100" before "20"; numeric sort puts 20 before 100.

Function signature:

string sortLines(vector<string> lines)

Example:

Input: lines = ["100", "20", "3", "10"]

Output: "3\n10\n20\n100"

When printed:
3
10
20
100

Pass a lambda comparator to std::stable_sort (not plain std::sort, which is not stable) that converts each operand to int via stoi and compares numerically.

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

STEP 1 OF 8
    Ctrl + Enter to check

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Sort V3 in C++, explained

    Problem overview

    Version 3 of the sort tool adds the -n flag. Each line of the vector<string> passed to sortLines is the text of a 32-bit integer: an optional leading -, no +, and possibly leading zeros such as "007". The function sorts the lines by numeric value, ascending, and returns the original strings joined with \n.

    Lines with the same value keep their input order, so this is a stable sort. An empty vector gives "". For {"100", "20", "3", "10"} the result is "3\n10\n20\n100". Sorted as text, "100" would come before "20", because '1' is smaller than '2'. That is the trap this version is about.

    Approach

    Keep the strings as they are, because the output must contain them unchanged, "007" included. Change only how two strings are compared: convert each to an int with stoi and compare the numbers. That makes a custom comparison, which sort and stable_sort accept as a third argument.

    Converting every line to an int, sorting the numbers and converting back with to_string would lose information: "007" would come back as "7", and the lesson's tests expect the original text. Sorting the strings with a numeric rule avoids the problem.

    Stability matters because different strings can have the same value. "7", "007" and "07" all mean 7. The lesson wants them to stay in the order they arrived. std::sort gives no such promise, but std::stable_sort does: elements that compare equal keep their relative order. It has the same interface as sort, so the switch is a single word.

    Converting inside the comparison means each string is parsed again every time it is compared. That costs a little extra work per comparison but keeps the code short, and the lines are short.

    Step by step

    1. Copy lines into sortedLines.
    2. Call stable_sort over the whole vector with a lambda as the third argument. The lambda takes two const string& parameters, a and b, and returns stoi(a) < stoi(b). It is true when a must go first. The references avoid copying the strings and const promises not to change them.
    3. Create an empty result string.
    4. Loop over the positions of sortedLines.
    5. Open an if for i > 0.
    6. Inside it, add a newline to result, so no newline precedes the first line.
    7. After the if, append sortedLines[i], the original text.
    8. Return result.

    The solution in C++

    class Solution {
    public:
        string sortLines(vector<string> lines) {
            vector<string> sortedLines = lines;
            stable_sort(sortedLines.begin(), sortedLines.end(), [](const string& a, const string& b) {
                return stoi(a) < stoi(b);
            });
            string result;
            for (int i = 0; i < sortedLines.size(); i++) {
                if (i > 0) {
                    result += "\n";
                }
                result += sortedLines[i];
            }
            return result;
        }
    };
    

    The details worth knowing:

    • A lambda is a function written in place. The [] is its capture list, which is empty here because the comparison needs nothing from the surrounding code. The parameter list and the body follow it.
    • stoi reads decimal. Leading zeros are fine and do not mean octal: stoi("007") is 7. Negative numbers work too: stoi("-20") is -20.
    • stoi can throw. A string that does not fit in an int, such as "2147483648", throws std::out_of_range, and a string with no digits, such as "abc", throws std::invalid_argument. The lesson guarantees 32-bit integers, so neither happens here.
    • Compare with <, don't subtract. A comparison like stoi(a) - stoi(b) can overflow for values near the ends of the int range, and signed overflow is undefined behaviour. It also returns an int, not the bool the algorithm expects.
    • Strict ordering. The comparison returns false for equal numbers. That is what lets stable_sort leave them where they are.

    Parsing each string once

    If the repeated parsing worried you, you could convert every line once, pair each number with its original text, and sort the pairs on the number:

    vector<pair<int, string>> keyed;
    for (const string& s : lines) keyed.push_back({stoi(s), s});
    stable_sort(keyed.begin(), keyed.end(), [](const auto& a, const auto& b) {
        return a.first < b.first;
    });
    

    Joining the second fields with the same loop gives "3\n007\n7\n07" for {"007", "7", "07", "3"}, the same answer as the lesson's code. For the short lines in this lesson the simpler version is enough, and it matches the steps above.

    Complexity

    A stable sort of n lines does O(n log n) comparisons when it can use extra memory, which stable_sort normally does; it falls back to a slower O(n log² n) method if that memory is not available. Each comparison parses two short strings. Building the result is one pass over the text. The extra space is the sorted copy and the result, plus the buffer the stable sort may allocate.

    Edge cases and common mistakes

    • Sorting as text. A plain sort on the strings turns {"100", "20", "3", "10"} into "10\n100\n20\n3". The numeric comparison gives "3\n10\n20\n100".
    • Negative numbers. {"-5", "3", "-20", "0"} gives "-20\n-5\n0\n3".
    • Equal values with different text. {"7", "007", "07"} keeps its order and gives "7\n007\n07". With {"007", "7", "07", "3"} the 3 moves to the front and the three sevens keep their relative order: "3\n007\n7\n07".
    • The limits of 32 bits. {"2147483647", "-2147483648", "0"} gives "-2147483648\n0\n2147483647".
    • Returning the numbers instead of the strings. The output must show each line as it came in, so "007" stays "007".
    • Empty input. No lines, no loop, result "".

    Testing

    linesresult
    {"100", "20", "3", "10"}"3\n10\n20\n100"
    {"-5", "3", "-20", "0"}"-20\n-5\n0\n3"
    {"007", "7", "07", "3"}"3\n007\n7\n07"
    {"2147483647", "-2147483648", "0"}"-2147483648\n0\n2147483647"
    {}""

    The next version builds on this one.

    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