Back to TILs

C++ partition

Date: 2023-04-05Last modified: 2023-06-27

Table of contents

  auto print = [](auto label, auto beg, auto end) {
    fmt::print("{:20} ", label);
    auto it = beg;
    while (it != end) {
      fmt::print("{:2} ", *it);
      it = std::next(it);
    }
    fmt::print("\n");
  };
  auto is_divisible_by_3 = [](int i) { return i % 3 == 0; };
  std::vector<int> numbers{5,  7,  4,  2,  8,  6,  1,  9,  0, 3,
                           18, 15, 14, 10, 13, 11, 12, 17, 16};
  print("numbers", std::begin(numbers), std::end(numbers));
  fmt::print("Are numbers partitioned? {}\n",
             std::is_partitioned(std::begin(numbers), std::end(numbers),
                                 is_divisible_by_3));

  auto firstElementOfSecondGroup =
      std::partition(begin(numbers), end(numbers), is_divisible_by_3);
  print("numbers", std::begin(numbers), std::end(numbers));
  fmt::print("Are numbers partitioned? {}\n",
             std::is_partitioned(std::begin(numbers), std::end(numbers),
                                 is_divisible_by_3));

  print("Side A", begin(numbers), firstElementOfSecondGroup);
  print("Side B", firstElementOfSecondGroup, std::end(numbers));

Possible output

numbers               5  7  4  2  8  6  1  9  0  3 18 15 14 10 13 11 12 17 16 
Are numbers partitioned? false
numbers              12 15 18  3  0  6  9  1  8  2  4  7 14 10 13 11  5 17 16 
Are numbers partitioned? true
Side A               12 15 18  3  0  6  9 
Side B                1  8  2  4  7 14 10 13 11  5 17 16 

References