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.
- Make a
stringstreamnamedssoverline. It lets you read the text piece by piece, the waycinreads input. - Declare a
stringnamedtokento receive each piece. - Loop
fieldtimes, withifrom 0 whilei < field. Reading exactly that many pieces leaves the wanted one intoken. - Read with
getline(ss, token, ',')inside the loop. The third argument makes the comma the delimiter, instead of the newline:getlinereads up to the next comma and discards it. - Return
tokenafter the loop. - In
sortLines, copylinesintosortedLines. - Call
stable_sortwith a lambda that capturesfield. The lambda takes twoconst string¶meters and returns whether the key ofais smaller than the key ofb, each found withextractField. - Create an empty
result. - Loop over the positions of
sortedLines. - Open an
iffori > 0. - Add a newline inside it.
- Append
sortedLines[i]after theif. - 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 usefieldand the code would not compile. The helper is astaticmember, so the lambda can call it without an object. getlinewith a delimiter.getline(ss, token, ',')replaces the contents oftokeneach time. An empty field gives an emptytoken, soextractField("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_sortkeeps them in input order. That matches the real command's-soption. - Passing by
constreference. Both the helper and the lambda takeconst 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": thewline first, then the twoxlines 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
sortinstead ofstable_sort. It may reorder lines with equal keys, which fails the tie cases. - Counting the pieces. The loop reads exactly
fieldpieces, so field 2 means two reads and the second piece is what remains intoken. Counting from 0 and stopping beforefieldis what makes the 1-indexed column number work directly. - Empty input.
sortLines({}, 1)returns"".
Testing
| lines | field | result |
|---|---|---|
{"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 | "" |
