C++判断分区是否为空

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

我正在使用 std::partition 将一个向量拆分为两个子向量。我想知道第一个分区是否为空

#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';
}

如何判断非零分区是否包含元素?

  • bound == v.begin() 当第一个分区为空时。
  • bound == v.end() 当第二个分区为空时。

此外,您还可以知道每个分区的大小。

std::distance(v.begin(), bound) 告诉第一个分区的大小

std::distance(bound, v.end())告诉第二个分区的大小