How to check if a partition is empty in c++

Viewed 79

I am using the std::partition to split a vector in two sub vectors. I want to know if the first partition is empty

#include <algorithm> 
#include <vector>
#include <iostream>

using namespace std;

int main() {
  vector<uint32_t> v {0,1,2,3,4,0,0,0};

  auto bound = std::stable_partition(v.begin(), v.end(), [](auto element)
  {
      return element > 0;
  });

  // print out content:
  std::cout << "non zeros";
  for (auto it=v.begin(); it!=bound; ++it)
      std::cout << ' ' << *it;
  std::cout << '\n';

  std::cout << "zeros";
  for (auto it=bound; it!=v.end(); ++it)
      std::cout << ' ' << *it;
  std::cout << '\n';
}

How to check if the non zeros partition contains elements or not?

2 Answers
  • bound == v.begin() when first partition is empty.
  • bound == v.end() when second partition is empty.

Furthermore, you can know the size of each partition.

std::distance(v.begin(), bound) tells the size of the first partition

std::distance(bound, v.end()) tells the size of the second partition

Related