Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::sort

Use case

Sort elements in ascending order (default) or by custom comparator (in case of complex types).

Explanation

Time complexity: O(n log n). Pick pivot + partitioning: n, recursing on each half: log n. See possible implementation.

Code

#include <algorithm>
#include <cstdint>
#include <print>
#include <string>
#include <vector>

struct Symbol {
  uint64_t address;
  std::string name;
};

int main() {
  std::vector<Symbol> symbols = {
      {0x10001000, "_main"}, {0x10003000, "_fini"}, {0x10002000, "_helper"}};

  std::sort(
      symbols.begin(), symbols.end(),
      [](const Symbol &a, const Symbol &b) { return a.address < b.address; });

  for (const auto &sym : symbols) {
    std::println("{:#x} {}", sym.address, sym.name);
  }

  return 0;
}

View on GitHub.

Output

$ ./src/algorithms/build/std-sort
0x10001000 _main
0x10002000 _helper
0x10003000 _fini