[c++] 특정 기간에 대한 통계 작업

이번에는 C++를 사용하여 특정 기간에 대한 통계 작업을 수행하는 방법에 대해 알아보겠습니다.

데이터 수집

가장 먼저, 특정 기간 동안의 데이터를 수집해야 합니다. 이 데이터는 파일에서 읽을 수도 있고, 데이터베이스에서 가져올 수도 있습니다. 예를 들어, 다음과 같이 파일에서 CSV 형식의 데이터를 읽을 수 있습니다.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

struct DataPoint {
    std::string date;
    double value;
};

std::vector<DataPoint> loadData(const std::string& filename) {
    std::vector<DataPoint> data;
    std::ifstream file(filename);
    std::string line;
    while (std::getline(file, line)) {
        size_t pos = line.find(",");
        if (pos != std::string::npos) {
            data.push_back({line.substr(0, pos), std::stod(line.substr(pos + 1))});
        }
    }
    return data;
}

통계 계산

특정 기간에 대한 통계를 계산하려면 해당 기간에 속하는 데이터만 선택하여 계산해야 합니다. 예를 들어, 특정 날짜 범위에 대한 평균 값을 계산하는 코드는 다음과 같을 수 있습니다.

#include <algorithm>

double calculateAverage(const std::vector<DataPoint>& data, const std::string& startDate, const std::string& endDate) {
    double sum = 0.0;
    int count = 0;
    for (const auto& point : data) {
        if (point.date >= startDate && point.date <= endDate) {
            sum += point.value;
            count++;
        }
    }
    return count > 0 ? sum / count : 0.0;
}

결과 출력

마지막으로, 계산된 통계를 출력해야 합니다. 예를 들어, 콘솔에 평균 값을 출력하는 코드는 다음과 같을 수 있습니다.

int main() {
    std::vector<DataPoint> data = loadData("data.csv");
    double avg = calculateAverage(data, "2022-01-01", "2022-01-31");
    std::cout << "Average for January 2022: " << avg << std::endl;
    return 0;
}

이제 코드를 실행하면 특정 기간에 대한 평균값이 출력될 것입니다.

이렇게 C++를 사용하여 특정 기간에 대한 통계 작업을 수행할 수 있습니다.

참고 문헌: