How to check if all the elements in a 2D vector are zero?

Viewed 432

I found on Stack Overflow that this single statement can be used to find whether all the elements of a vector are zero, or not, but this is only for 1D vector.

bool zeros = std::all_of(v.begin(), v.end(), [](int i) { return i==0; });

How can I modify it so that it can work for a 2D vector?

Is it possible to implement it by just using a single statement?

2 Answers

Like this (assuming you mean a nested vector):

#include <algorithm>
#include <vector>

int main() {
  std::vector<std::vector<int>> vs;

  std::all_of(vs.begin(), vs.end(), [](const std::vector<int>& v) {
    return std::all_of(v.begin(), v.end(), [](int x) { return x == 0; });
  });
}

You could also do something like this:

bool check0(const std::vector<std::vector<int>> &vs) {
    for(const auto& v : vs) {
        for(auto x : v) {
            if(x != 0) {
                return false;
            }
        }
    }
    return true;
}

You can compare the disassembly of both versions here: https://godbolt.org/z/YzdW7x.

You can join the 2D vector into a single range, and apply all_of on that:

auto is_zero = [](int i) { return i==0; };  // some predicate

// vs is some 2D range
bool zeros = std::ranges::all_of(vs | std::views::join, is_zero);  

Here's a demo.

Related