Counting Algorithms

How to Count Elements in a Multi-Dimensional Container

How do I count elements in a multi-dimensional container?

Abstract art representing computer programming

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.

This Question is from the Lesson:

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved