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()

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

How to Count Elements in a Custom Container Using std::ranges::count()
How can I count elements in a custom container using std::ranges::count()?
Using Member Functions as Predicates with std::ranges::any_of()
How can I use std::ranges::any_of() with a member function that requires parameters?
Performance of std::ranges Algorithms vs Traditional Loops
How do std::ranges algorithms compare with traditional loops in terms of performance?
Customizing Predicates for std::ranges::count_if()
How can I customize the behavior of std::ranges::count_if() for specific data types?
Using std::ranges Algorithms with Container Views
How do std::ranges algorithms interact with container views like std::span or std::string_view?
Real-World Examples of Using std::ranges::none_of()
What are some real-world examples of using std::ranges::none_of() in software development?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant