Start learning free

LESSON 21 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V1 in C++: sort() on a vector of strings

Practice Read the full explanation

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

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Sort V1 in C++, explained

    Problem overview

    This is the first version of a small sort command-line tool. The method sortLines receives a vector<string> and returns one string: the lines in ascending order, separated by \n. Duplicates stay, and an empty vector gives the empty string.

    The order is by character code, as in LC_ALL=C sort. Uppercase letters come before lowercase ones, so "Zebra" sorts before "apple", and an empty line sorts first. With {"banana", "apple", "cherry"} the function returns "apple\nbanana\ncherry".

    Approach

    There are two jobs: put the lines in order, then join them into one string. The standard library does the first. std::sort from <algorithm> compares std::string values with operator<, which compares them character by character using the character codes. That is exactly the order the lesson asks for, so no custom comparison is needed.

    C++ has no built-in way to join strings with a separator, so the second job is a loop that appends each line to a result string and puts a newline in front of every line except the first. That "separator before every item but the first" pattern gives no newline at the start and none at the end.

    Other containers could keep lines ordered as you insert them. A multiset<string> does, and unlike a plain set it keeps duplicates. A vector and one call to sort is simpler here, because all the lines arrive at once and the result is built from a vector anyway.

    The comparison does not depend on the machine's language settings. std::string compares raw character codes, which is why the lesson describes the behaviour of LC_ALL=C sort and not of a sort that follows dictionary rules for a locale.

    Step by step

    1. Copy the vector. The parameter lines is already a copy of the caller's vector, since it is passed by value. The lesson still copies it into sortedLines, which keeps the original order available under its own name.
    2. Sort the copy in place. sort takes the range to reorder: begin() to end().
    3. Create an empty result string to build the output in.
    4. Loop over the positions from 0 to sortedLines.size() - 1.
    5. Add a newline before every line except the first, by testing i > 0.
    6. Append the line sortedLines[i] to result.
    7. Return result after the loop.

    The solution in C++

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

    A few details are worth knowing:

    • The range is half-open. end() points one past the last element, so sort(v.begin(), v.end()) sorts the whole vector.
    • Strings compare by character code. With the default operator<, "Zebra" is smaller than "apple" because 'Z' is 90 and 'a' is 97. A shorter string that is a prefix of a longer one comes first, and "" is smaller than everything else.
    • Numbers sorted as text. The lines are strings, so {"10", "9", "1"} becomes "1\n10\n9": '1' is smaller than '9', so "10" comes before "9". Sorting by numeric value is a different task.
    • size() is unsigned. The loop compares an int with sortedLines.size(), which is an unsigned type. That is fine here because i never goes below 0, but it is the reason v.size() - 1 wraps around to a huge number on an empty vector.
    • sort is not stable. Equal strings are indistinguishable, so it doesn't matter here.

    Complexity

    Sorting n lines takes O(n log n) comparisons, and each comparison can cost up to the length of the shorter string. Building the result touches every character once, which is linear in the total text size. The copy and the result string need extra space proportional to the input.

    Why copy first?

    Sorting in place changes the vector it is given. Working on sortedLines instead of lines makes it clear which vector is the sorted one and leaves lines in its original order if you later need it, for example to compare before and after. Because lines is passed by value, the caller's own vector would be safe either way. For a large vector you would normally pass it by reference to avoid the copy, but the lesson's signature takes it by value.

    Edge cases and common mistakes

    • An empty vector. The loop never runs and the function returns "".
    • Empty lines. An empty string sorts first. {"apple", "Zebra", ""} becomes "\nZebra\napple", which starts with a newline because the first line is empty.
    • Duplicates. {"b", "a", "b"} gives "a\nb\nb": all copies are kept.
    • A trailing newline. Adding "\n" after every line instead of before all but the first produces an extra newline at the end and fails the tests.
    • Sorting with a hand-written loop. Writing your own bubble sort works but is slower and easier to get wrong. std::sort is the idiomatic tool.

    Testing

    Try these inputs in the editor above. The results are the strings the function returns, with each newline written as \n:

    linesresult
    {"banana", "apple", "cherry"}"apple\nbanana\ncherry"
    {"apple", "Zebra", ""}"\nZebra\napple"
    {"b", "a", "b"}"a\nb\nb"
    {"10", "9", "1"}"1\n10\n9"
    {}""

    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