Introduction to Data Aggregation Methods

Welcome to today's lesson! Our topic for the day is data aggregation, a crucial aspect of data analysis. Like summarizing a massive book into key points, data aggregation summarizes large amounts of data into important highlights.

By the end of today, you'll be equipped with several aggregation methods to summarize data streams in C++. Let's get started!

Basic Aggregation Using Built-in Functions

Let's say we have an array of integers denoting the ages of a group of people. We will demonstrate several basic aggregation methods using C++'s built-in functions:

#include <iostream>
#include <vector>
#include <numeric>    // For std::accumulate
#include <algorithm>  // For std::min_element, std::max_element

int main() {
    std::vector<int> ages = {21, 23, 20, 25, 22, 27, 24, 22, 25, 22, 23, 22};

    // Number of people
    int num_people = ages.size();
    std::cout << "Number of people: " << num_people << std::endl;

    // Total age
    int total_ages = std::accumulate(ages.begin(), ages.end(), 0);
    std::cout << "Total age: " << total_ages << std::endl;

    // Youngest age
    int youngest_age = *std::min_element(ages.begin(), ages.end());
    std::cout << "Youngest age: " << youngest_age << std::endl;

    // Oldest age
    int oldest_age = *std::max_element(ages.begin(), ages.end());
    std::cout << "Oldest age: " << oldest_age << std::endl;

    // Average age
    double average_age = static_cast<double>(total_ages) / num_people;
    std::cout << "Average age: " << average_age << std::endl;

    // Age range
    int age_range = oldest_age - youngest_age;
    std::cout << "Age range: " << age_range << std::endl;

    return 0;
}

Here's a brief overview of the above code snippet:

  1. Number of people: Uses ages.size() to get the number of elements in the vector.
  2. Total age: Uses std::accumulate from the <numeric> header to sum all elements in the vector.
  3. Youngest age: Uses std::min_element from the <algorithm> header to find the smallest element.
  4. Oldest age: Uses std::max_element from the <algorithm> header to find the largest element.
  5. Average age: Calculates the average age by dividing the total age by the number of people.
  6. Age range: Computes the range of ages by subtracting the youngest age from the oldest age.

These functions provide essential aggregation operations and are widely used with data streams.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal