【问题标题】:How to check if a partition is empty in c++如何在c ++中检查分区是否为空
【发布时间】:2020-11-12 17:49:10
【问题描述】:

我正在使用 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';
}

如何检查非零分区是否包含元素?

【问题讨论】:

    标签: c++ stl


    【解决方案1】:
    • bound == v.begin() 第一个分区为空时。
    • bound == v.end() 第二个分区为空时。

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 如果大小为0,则为空。
      猜你喜欢
      • 2011-06-27
      • 1970-01-01
      • 2013-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多