How to Count Elements in a Multi-Dimensional Container
How do I count elements in a multi-dimensional container?
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:
- We have a 2D vector
Numbers
containing integers. - The lambda function
isFour()
checks if a given number is 4. - We use a loop to iterate through each row of the 2D vector and apply
std::ranges::count_if()
to count the number of 4s in each row. - The counts from each row are accumulated in the
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.
Counting Algorithms
An introduction to the 5 main counting algorithms in the C++ standard library: count()
, count_if()
, any_of()
, none_of()
, and all_of()