Video Coming Soon...

Created by Zed A. Shaw Updated 2026-04-30 02:05:52

41: sort

Don't over think it. Implementing sort with the C++ standard library is very easy. All sort does is sort the lines of its input or a file. That's it.

The Challenge

This challenge is more about researching on cppreference.com than implementing a sorting algorithm. Your job is to find out what is available already in C++ that will do the sorting for you.

The Code

If you get desperate peek very quickly at my solution.

See my first version of sortView Source file sort.cpp Only

#include <fmt/core.h>
#include <iostream>
#include <unistd.h>
#include <fstream>
#include <vector>
#include <algorithm>

void sort_file(std::istream& in) {
  std::string line;
  std::vector<std::string> lines;

  while(in) {
    getline(in, line);
    lines.emplace_back(line);
  }

  std::sort(lines.begin(), lines.end());

  for(auto& line : lines) {
    fmt::println("{}", line);
  }
}


int main(int argc, char* argv[]) {
  if(argc > 1) {
    for(int i = 1; i < argc; i++) {
      std::ifstream in_file{argv[i]};
      sort_file(in_file);
    }
  } else {
    sort_file(std::cin);
  }
}

The Discussion

Implementing various sorting algorithms is a fun academic exercise, but you should use established sorting methods unless you've got a really good reason. In fact, using the standard library is almost always what you should do before trying to write your own.

That being said, it's important to learn how these APIs in the standard library work. The best way to learn how something works in programming is to make your own. You don't have to make an amazing professional competitor. Even a simple naive version of it will teach you more about how it works.

Further Study

Implement more of the options to sort before moving on to uniq.

Previous Lesson Next Lesson

Register for Learn C++ the Hard Way

Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.