Counting elements in a multi-dimensional container requires iterating through each dimension. Here's how you can do it with std::ranges::count_if()
for a 2DÂ vector:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<std::vector<int>> Numbers{
{1, 2, 3},
{4, 4, 5},
{6, 7, 8}
};
auto isFour{[](int x) { return x == 4; }};
int count = 0;
for (const auto& row : Numbers) {
count += std::ranges::count_if(row, isFour);
}
std::cout << "Count of fours: " << count;
}
Count of fours: 2
In this example:
Numbers
containing integers.isFour()
checks if a given number is 4.std::ranges::count_if()
to count the number of 4s in each row.count
variable.This approach can be extended to higher-dimensional containers by adding more nested loops. For instance, for a 3D vector, you would need an additional loop to iterate through each 2DÂ sub-vector.
By using std::ranges::count_if()
within the appropriate nested loops, you can count elements in multi-dimensional containers efficiently, taking advantage of the power and flexibility of C++20Â ranges.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the 5 main counting algorithms in the C++ standard library: count()
, count_if()
, any_of()
, none_of()
, and all_of()