The problem of finding the first all zero row in a NxN matrix was featured in a letter to the CACM in 1974 by Frank Rubin who claimed it was a problem for which using a GOTO
was better than alternatives.
But many languages have labeled break statements and other features that make the problem trivial. In fact, in JavaScript we need only write:
a.findIndex(row => row.every(x => x === 0))
which gives us the index of the first nonzero row or -1 if no such row exists. I'm interested in implementing this functional approach in C++ 14. As I don't have a huge amount of C++ experience, I came up with:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>
using namespace std;
bool isAllZeroRow(const vector<int>& row) {
return all_of(row.begin(), row.end(), [](int x){return x==0;});
}
int firstAllZeroIndex(const vector<vector<int>>& m) {
return distance(m.begin(), find_if(m.begin(), m.end(), isAllZeroRow));
}
vector<vector<int>> matrix1 = {{1, 2}, {0, 0}, {1, 1}};
vector<vector<int>> matrix2 = {{0, 0, 1, 2}, {3, 0, 0}, {0, 0, 0}};
vector<vector<int>> matrix3 = {{0, 0, 1, 2}, {3, 0, 0}, {0, 0, 5}};
int main() {
assert(firstAllZeroIndex(matrix1) == 1);
assert(firstAllZeroIndex(matrix2) == 2);
assert(firstAllZeroIndex(matrix3) == 3); // not found
cout << "ok\n";
}
I'm interested in hearing things like:
- whether the lambda is okay, or should it be a named function or a C++ unary predicat
- Are
distance
andfind_if
best expressed with iterators like I have done here? - Was it right to use the helper function, or is there a way in C++ to make things almost as concise as the JavaScript solution?
I know how to do this function with nested loops with a return
in the inner loop, but I'm intrigued by trying out the functional forms and was wondering how I did.
<functional>
. and iterators vs. collection-specific methods, if any. Only "requirements" are to employ the most idiomatic uses of the standard library possible. \$\endgroup\$all_of
is perfectly safe; it returns as soon as it finds an element not meeting the condition. \$\endgroup\$